Ruby: Method chaining

Interesante 馃檪


module MethodDecorator
  # Create a chain between methods:
  #   Rename org_mthd to org_alias and then point it to new_mthd
  # The next time org_mthd is called new_methd will be executed
  def add_chain org_mthd, new_mthd, org_alias
    self.class.class_eval do
      (alias_method org_alias, org_mthd) unless method_defined? org_alias
      alias_method org_mthd, new_mthd

  # Extremly evil code ahead!
  def decorate method, decorator
    # Create a chain counter if it doesn't exist
    @chain_counter ||= 0
    # Use the chain counter as a method id
    i = (@chain_counter += 1)

    # Create a new method which will dispatch the call to both
    # the original and the decorator method
    self.class.class_eval <<-EOM
      def chain_dispatcher#{i} *params
        #{decorator} *params
        chain_original#{i} *params

    # Once the method was created, add chain
    eval "add_chain method, :chain_dispatcher#{i}, :chain_original#{i}"

class Foo
  include MethodDecorator
  def foo; print "Hello "; end
  def bar; print "worldn"; end
  def initialize; decorate :bar, :foo; end

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

Edit: Agregado el plugin para c贸digo!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s