Ruby : create classes on fly

15 May 2013

This is a simple blog post which demonstrate how we can create ruby classes on the fly.

Using class keyword and Class.new

We can create a ruby class either using class keyword or using Class constructor. Ruby newbies will be only familiar with class keyword, but in order to create a class on the fly we need to use Class constructor

Creating simple ruby class

Here is how we can create a simple class on the fly using Class constructor.
The above code will create a new class when you call the instance method create_class.
In most cases the new class name will be on some variable. So we need to use const_get method to the new class.
Object.const_get("airtel".classify).new.hello_class   
I required "active_support/inflector" to get the method classify. what const_set method is doing is sets a constant to the given object, here sets the class name.
If you want the newly created class to be a part of SomeModule then you need to use const_set on SomeModule like
then while const_get use
SomeModule.const_get('airtel'.classify)  

Creating inherited class

If you understand how to create a simple class, then creating a inherited class is quite simple. You just need to pass the parent class to the Class constructor.

This will create a new class inherited from SomeModule::Test.

self.class.ancestors will print the hierarchy like [SomeModule::Airtel, SomeModule::Test, Object, Kernel, BasicObject].


Am I missed something? Love to hear from you via comments.
Blogged via Markdown Blogger
If you particularly enjoy my work, I appreciate donations given with Gittip.
comments powered by Disqus