Advanced Ruby – Dynamic code execution

One of the advanced features of Ruby, which is behind the success of rails is the dynamic code execution. Code fragments can be executed using eval method. This is very similar to JavaScript eval function.

following is an example,

eval "x =10; puts x;" # print 10 using dynamic code execution

eval executes the code in the current context. It is also possible to execute the code in a different context.

Code can also be executed in class context using another method class_eval. class_eval can add methods due to a class during execution! In the following example, we add a method doHello to the Sample class during execution of initialize. Then we execute doHello!

class Sample
  def initialize
    Sample.class_eval "def doHello; puts 'Hello World';end"
  end
  m = Sample.new
  m.doHello
end

Now this is the technique which is behind the secret of attr_accessor used in classes. In fact attr_accessor is just a method. We will try to create a similar functionality using attr_accessor2. All the classes in Ruby are subclassed automatically from the class Class. Hence we will modify Class and add attr_accessor2 method which in turn will add getter and setter methods for the passed variable!

class Class
  def attr_accessor2(var_name)
    string_val = "def #{var_name}; "+
                 "   @#{var_name}; "+
                 "end; "+
                 "def #{var_name}=(value);"+
                 "   @#{var_name} = value;"+
                 "end; "
   self.class_eval string_val
  end
end

# Using the new attribute accessor method!
class M
  attr_accessor2 :test_var

  m = M.new
  m.test_var = "hello"
  puts m.test_var
end

3 Responses to “Advanced Ruby – Dynamic code execution”

  1. Dude, this post helped me no end. I had been trying for ages to modify the attr_accessor method in rails and having read and followed your examples I was totally successful.
    Cheers for sharing.

  2. From your example above is there a way to export or print out the Dynamic Code that is created?

    CHW

  3. Sorry – let me add on more thought to the post above. Is it to print out the generated code after its been eval ?

Leave a Reply