How do I un-namespace a ruby constant? -


i using library doesn't handle namespaced models. have rails engine has activerecord models need use , such reference them namespace of engine, ex: tableengine::posts.

is there way in ruby un-namespace posts class?

something

tableengine::posts.demodulize # => posts 

at first can add constant need , assign class/module (remember both objects). should duplicate reset name:

posts = tableengine::posts.dup 

afterwards remove source constant name:

object.send :remove_const, :tableengine 

then:

posts # => posts tableengine # => nameerror: uninitialized constant tableengine tableengine::posts # => nameerror: uninitialized constant tableengine 

update. why dup needed:

notice, class someclass shortcut creating object of type class , assigning constant:

someclass = class.new 

when create class, name value isn't set:

klass = class.new # => #<class:0x00000001545a28> klass.name # => nil 

when assign constant first time, name assigned , memoized:

klass = klass # => klass klass.name # => "klass" 

when later assign object of type class constant, remains same object, referred both constants:

newklass = klass # => klass klass.name # => "klass" newklass.name # => "klass" 

that's why if initial constant removed, object keep carrying old name.

object.send :remove_const, :klass # => klass newklass # => klass newklass.name # => "klass"  klass # => nameerror: uninitialized constant klass 

the object hasn't been changed. has been changed list of constants, carried object object.

when duplicate object of type class created without name (it new object):

new_klass = newklass.dup # => #<class:0x000000016ced90> new_klass.name # => nil 

and when assing new constant, name set. how in first example above receives new name:

posts = tableengine::posts.dup # => post 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -