Discover Dynamic Object Creation In Ruby

Let me quickly explain Ruby‘s dynamic object creation. When I talk about dynamic object creation, I’m referring to when you instantiate a new object instance from meta-data using a class (also referred to a as a Type in .NET) name, or class meta-data object. In languages like C#, and Java you will use reflection to dynamically invoke objects like this. Ruby has two equivalents, depending on whether you’re invoking an object from a class’s name or a class meta-data object. Invoking an object from a class meta data object is very straight forward:

class_meta_obj = Module1::Module2::Module3::SomeClass

All you do to instantiate a new object instance from a class definition, is to call new on it.

Invoking an object from a class name is more cumbersome than I think is necessary, because you first need to load each module in the full class name:

class_name = "Module1::Module2::Module3::SomeClass"
result_class_meta_obj = class_name.split('::').inject(Object)
{ |result_class_meta_obj, item|
    result_class_meta_obj.const_get item

First we split the module & class hierarchy on the separator “::”. This gives us each individual module and class in an Array. For each item in the array we pass in the last result returned by the block (result_class_meta_obj), and the current module or class name (item). The argument passed to the inject method (Object) is the first iteration’s last result (result_class_meta_obj).

On the class/module meta object we send the current module/class’s name to const_get. This returns the current module/class’s meta data object, that then becomes the latest result. Each class and module name is a constant in Ruby that points to its corresponding class/module definition. Now that we have the class definition meta data object, we can invoke its constructor the same way as in the first example.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s