Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails getting module with constantize

I have a class under the namespace of a module, say

Module::Klass

I am able to access Klass from the console and it gives me :

Module::Klass

However, if I try to use:

"klass".constantize # Calling constantize on String

It errors out as it doesn't append the module namespace.

So, My question is : Is there a way to constantize the string according to its current context, so that I receive the klass name along with its module ?

like image 757
Nerve Avatar asked Nov 28 '22 15:11

Nerve


1 Answers

If by "current context" you mean that you are currently within that module, you can access its constants directly.

module Foo
  class Bar
  end

  self.const_get('Bar') # => Foo::Bar
end

You can, of course, do it if you're outside of Foo.

Foo.const_get('Bar') # => Foo::Bar
like image 160
Sergio Tulentsev Avatar answered Dec 05 '22 23:12

Sergio Tulentsev