I am using a library that doesn't handle namespaced models. I have a rails engine that has all the ActiveRecord models that I need to use and as such I reference them with the namespace of the engine, ex: TableEngine::Posts.
Is there a way in Ruby to un-namespace the Posts class?
something like
TableEngine::Posts.demodulize # => Posts
At first you can add the constant you need and assign the Class/Module to it (remember both are just objects). You should duplicate it to reset the name:
Afterwards remove the source constant name:
Then:
UPDATE. Why
dupis needed:Notice, the
class SomeClassis a shortcut for creating an object of typeClassand assigning it to some constant:When you create a class, its name value isn't set:
When you assign it to the constant for the first time, the name is assigned and memoized:
When you later assign the object of type
Classto another constant, it remains just the same object, referred by both constants:That's why even if the initial constant will be removed, the object will keep carrying the old name.
The object by itself hasn't been changed. What has been changed is the list of constants, carried by the
Objectobject.When you duplicate the object of type
Classit is created without any name (it is the new object):And when you assing it to the new constant, the name is set. That is how in the very first example above it receives the new name: