SULAIR Home

Dynamically defining an object's methods through metaprogramming

Today I began looking into how to dynamically create methods in Ruby for a certain use case I had.

Basically what I wanted to do was to have methods dynamically added to an object based on what was present at the time of instantiation (similar to ActiveRecord).

So:
ab = Obj.new({:a=>"val_a",:b=>"val_b"})
yz = Obj.new({:y=>"val_y",:z=>"val_z"})
Should return objects that can respond to a and b or y and z respectively.
ab.a #=>"val_a"
ab.b #=>"val_b"
  
yz.y #=>"val_y"
yz.z #=>"val_z"

Syndicate content
« Back