Undefining class at runtime
This post explains undefining the class at runtime.
Im not gonna explain the live-cases where this might be used. Ask Uncle Google for that.
Lets jump in at d code directly.
When u create a new class, say “Person”, two things happen:
- A new object of type(class) Class is instantiated.
- A new constant called Person will be instantiated and will hold the value of the class-object created above.
Proof: Class Person;end;
Try, Person.class #=> Class. This means that the Person holds a value which is of class Class. (1 is proved).
Try, Person = 123 #=> Curses saying, Person is already initialized, which means Person is a constant. (2 is proved).
Now, All the constants(Person) and other are silently ducked into the class Object.
Proof: Object.class_eval{Person} #=> Person Class
So, we should understand by now that the newly created class Person resides as a constant of the class Object.
So if we could somehow remove that constant, then the class Person will also be removed.
There is a method called remove_const for the class Object.
So, try Object.remove_const : Person #=> Curses, NoMethodError: private method `remove_const’ called for Object:Class
This is becoz, remove_const is a private method of Object class.
So the worry now is, how to invoke a private method.
We have two solutions:
- Object.send(:remove_const , : Person)
- Object.class_eval{remove_const : Person}
Now try, Person.new. # Curses, uninitialized constant Person
Voila, job done. Very rarely does an ERROR MESSAGE makes us feel happy. Well, kind of an article.
You can learn much about class_eval from this very good article by Khaled.