Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the namespace/module name programmatically in Ruby on Rails?

How do I find the name of the namespace or module 'Foo' in the filter below?

class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = ???
  end
end


class Foo::BarController < ApplicationController
  before_filter :get_module_name
end
like image 588
Steropes Avatar asked Sep 25 '08 13:09

Steropes


People also ask

What is namespace in Ruby on Rails?

A namespace is a container for multiple items which includes classes, constants, other modules, and more. It is ensured in a namespace that all the objects have unique names for easy identification.

How do you reference a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

What is module function in Ruby on Rails?

A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword. Important Points about Modules: You cannot inherit modules or you can't create a subclass of a module. Objects cannot be created from a module.


3 Answers

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]
like image 64
Jason Harrelson Avatar answered Oct 25 '22 12:10

Jason Harrelson


For the simple case, You can use :

self.class.parent
like image 44
Hettomei Avatar answered Oct 25 '22 14:10

Hettomei


This should do it:

  def get_module_name
    @module_name = self.class.to_s.split("::").first
  end
like image 21
Daniel Lucraft Avatar answered Oct 25 '22 13:10

Daniel Lucraft