Nicolás Brailovsky


A modern blog

Ruby: Method chaining

author Posted by: nico on date Oct 16th, 2008 | filed Filed under: Programming

Interesante :)

  1. #!/usr/bin/ruby1.8
  2.  
  3. module MethodDecorator
  4.   # Create a chain between methods:
  5.   #   Rename org_mthd to org_alias and then point it to new_mthd
  6.   # The next time org_mthd is called new_methd will be executed
  7.   def add_chain org_mthd, new_mthd, org_alias
  8.     self.class.class_eval do
  9.       (alias_method org_alias, org_mthd) unless method_defined? org_alias
  10.       alias_method org_mthd, new_mthd
  11.     end
  12.   end
  13.  
  14.   # Extremly evil code ahead!
  15.   def decorate method, decorator
  16.     # Create a chain counter if it doesn’t exist
  17.     @chain_counter ||= 0
  18.     # Use the chain counter as a method id
  19.     i = (@chain_counter += 1)
  20.  
  21.     # Create a new method which will dispatch the call to both
  22.     # the original and the decorator method
  23.     self.class.class_eval <<-EOM
  24.       def chain_dispatcher#{i} *params
  25.         #{decorator} *params
  26.         chain_original#{i} *params
  27.       end
  28.     EOM
  29.  
  30.     # Once the method was created, add chain
  31.     eval "add_chain method, :chain_dispatcher#{i}, :chain_original#{i}"
  32.   end
  33. end
  34.  
  35. class Foo
  36.   include MethodDecorator
  37.   def foo; print "Hello "; end
  38.   def bar; print "world\n"; end
  39.   def initialize; decorate :bar, :foo; end
  40. end
  41.  
  42. Foo.new.bar

Ahora si, tengo que buscar ya un plugin para código.

Edit: Agregado el plugin para código!