add attribute at runtime
I’m all excited abt this post.
Coz this is something i learnt just now, and consider it my best learning till now in RUBY.
Q: How to add attributes to a class at runtime?
A:
class Class
def new_attr (attr_name)
class_eval {attr_accessor :"#{attr_name}"}
end
end
class_eval : Evaluates a string or a block in the context of the receiver, here the class.
Explanation:
1) We defined a new method to the CLASS called new_attr, which is intended to add new attributes at runtime.
2) This method needs the name of the new attribute to be passed.
3) In the definition, it calls class_eval, which means “DO SOMETHING AT THE CLASS LEVEL”
4) What to do is specified in the block after the class_eval, which says : attr_accessor “#{attr_name}”, which will become attr_accessor :name when we call new_attr(‘name’).
5) We know that attr_accessor is rails syntactic sugar to create the a specific instance variable, and its set/get (read/write) methods. So here, when we call new_attr(‘name’), its creating a new instance variable (@name) and 2 new methods ‘name” and “name=”.
Try this;
class Person; end;
This creates a bare class Person.
p = Person.new
Try, p.name, it throws an error cursing “Undefined method name”.
Its fairly expected coz, Person has no attribute called name.
Now, say Person.new_attr(‘name’)
now try, p.name, it will not curse you.
To check, try Person.singleton_methods.include?(“name”)
This says TRUE.
Hope this article comes handy.
charles said,
February 17, 2011 at 2:40 am
I don’t think Person.singleton_methods.include?(“name”) will return true, maybe you mean p.public_methods.include?(:name).
Thank you for this article, it’s very userful.