Monday, November 12, 2012

Simply Complex

Well .. I was reading through the Pragmatic Programmer's Guide and saw this piece of code.

def ExampleDate.once(*ids)
  for id in ids
    module_eval <<-"end_eval"
      alias_method :__#{id.to_i}__, #{id.inspect}
      def #{id.id2name}(*args, &block)
        def self.#{id.id2name}(*args, &block)
          @__#{id.to_i}__
        end
        @__#{id.to_i}__ = __#{id.to_i}__(*args, &block)
      end
    end_eval
  end
end

The guide said "Note that this redefinition uses the fact that methods may contain nested singleton method definitions, a clever trick." ..

Essentially the problem is to check if the value exists for the a variable. If not then do some calculations and set the instance variable. Then return that variable for all further calls to the instance method.

This variation does something unique.

First it makes an alias for the method which checks the if .. else. It redefines the name of the method to be __278626__ . The number signifies the identification number assigned for the symbol. This is done inside the module eval which adds stuff to the class which calls the once method like so.

once :abc, :def

The method is first declared with args and blocks. Then if you notice there is a self method declared too. The first fact is that we dont care whats in the instance method code block unless it is executed. For it to be executed, it should be called from an instance. Therefore when the method does get called, it is redefined in the scope of the object, ie the same method is redefined to return an instance variable. The call continues then to set the instance variable which is to be returned by the redefined method.

phew.