house9

random code and what not

Ruby Notes - part 1 - dynamic object creation

I am starting to learn Ruby and Rails (just for fun) - took awhile to find a good example of creating an object at runtime given a string representing the objects name; finally came across this post http://www.ruby-forum.com/topic/96222;

in theses 2 examples - given an ActiveRecord object ‘Project’ and a database table named ‘projects’, invoke the Project and execute some methods on it

# using eval
def test_dynamic_invoke_with_eval
__object_name = “Project”
__o = eval(object_name)

__p “object name is ‘” + o.to_s + ”’”
__p “object table name is ‘” + o.table_name + ”’”
end



# using Object.const_get
def test_dynamic_invoke_with_object_const_get
__object_name = “Project”
__o = Object.const_get(object_name)

__p “object name is ‘” + o.to_s + ”’”
__p “object table name is ‘” + o.table_name + ”’”
end



Check the ruby forum link above as well - the last entry posted by ‘unknown (Guest)’; this is probably the true ruby way to do it? extend the String object with a helper method so you can turn any string into an object? code from that post

# extend String
class String
__def to_class
___Object.const_get(self)
__end__
end

Comments

Ahmed
Thank you very much for this article! It helped me creating an array from a string that represents nested arrays inside it (tree) without the need to parse the string to identify braces.

Best,
Ahmed Nabhan