All of the code samples have now been consolidated and moved to my blog at Many google searches still point here so I am leaving this blog operational.

Saturday, September 1, 2007

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;

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 + "'"

# 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 + "'"

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


Ahmed said...

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.

Ahmed Nabhan

Doug said...

Sweet! Just what I was looking for. Thanks so much.

Custom Search
< ... back