From: why the lucky stiff Date: 2002-07-25T14:25:39+09:00 Subject: Re: A Code Challenge Tom Sawyer (transami@transami.net) wrote: > Problem: > > given a proc p and an object o with method x, such that the arity of x > and p are the same, dynamically append p into x. > not too elegant but a starting point: class Object # meth is aSymbol, p is aProc ;) def append_proc_to_method( meth, &p ) # check arity if method( meth ).arity.abs != p.arity.abs raise ArgumentError, "Arity doesn't match #{type}##{meth.id2name} and #{p.inspect}" end # stores procs in this instance var @__proc_add__ ||= {} unless @__proc_add__.has_key?( meth ) @__proc_add__[meth] = [p] # eval is a code smell but oh oh well type.module_eval <<-"end;" alias_method :__#{meth.to_i}__, :#{meth.id2name} private :__#{meth.to_i}__ def #{meth.id2name}( *args ) __#{meth.to_i}__( *args ) if @__proc_add__.is_a? Hash if @__proc_add__.has_key?( :#{meth.id2name} ) @__proc_add__[:#{meth.id2name}].each { |p| p.call( *args ) } end end end end; else @__proc_add__[meth] << p end end end # Simple test class O def x(a) puts "do something with #{a}" end end # Add two procs to this instance's x meth o = O.new p = Proc.new { |a| puts "do something else with #{a}" } o.append_proc_to_method( :x, &p ) o.append_proc_to_method( :x ) { |a| puts "do another something else with #{a}" } o.x(2) # Make sure this instance's x is still just running the original o2 = O.new o2.x(4) _why