Dan Rosenstark Dan Rosenstark - 1 year ago 52
Ruby Question

Force Class Loading and Unloading (RoR)

I am loading a class from a string like this

Kernel.const_get(some_class_name).new


which works, but what is the correct way to do this?

More importantly, is there any way to unload a class? I have tried

Object.send(:remove_const, some_class_name)


but that is not the same as before the class was ever loaded.

Note: related to this.

Answer Source

Since you tagged the question with Rails, then you can do

some_class_name.constantize

Example

"User".constantize
# => User

remove_const works, but you need to call it from the object space where the constant is defined. Also, remember to pass a symbol as the constant name.

Example

Object.send(:remove_const, :Foo)