How do you find the namespace/module name programmatically in Ruby on Rails?
For the simple case, You can use :
self.class.parent
This should do it:
def get_module_name
@module_name = self.class.to_s.split("::").first
end
For Rails 6.1
self.class.module_parent
Hettomei answer works fine up to Rails 6.0
DEPRECATION WARNING:
Module#parent
has been renamed tomodule_parent
.parent
is deprecated and will be removed in Rails 6.1.
None of these solutions consider a constant with multiple parent modules. For instance:
A::B::C
As of Rails 3.2.x you can simply:
"A::B::C".deconstantize #=> "A::B"
As of Rails 3.1.x you can:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )
This is because #demodulize is the opposite of #deconstantize:
"A::B::C".demodulize #=> "C"
If you really need to do this manually, try this:
constant_name = "A::B::C"
constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]