Rails 3: Get current namespace?
Solution 1
You can use:
self.class.parent == Admin
Solution 2
Outside the controller (e.g. in the views), use controller.class.name. You can turn this into a helper method like this:
module ApplicationHelper
def admin?
controller.class.name.split("::").first=="Admin"
end
end
Solution 3
In both the controller and the views, you can parse controller_path, eg.:
namespace = controller_path.split('/').first
Solution 4
Not much more elegant, but it uses the class instead of the params hash. I am not aware of a "prepared" way to do this without some parsing.
self.class.to_s.split("::").first=="Admin"
Solution 5
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]
arnekolja
Updated on March 28, 2020Comments
-
arnekolja about 4 years
using a method :layout_for_namespace I set my app's layout depending on whether I am in frontend or backend, as the backend is using an namespace "admin".
I could not find a pretty way to find out which namespace I am, the only way I found is by parsing the string from params[:controller]. Of course that's easy, seems to be fail-safe and working good. But I am just wondering if there's a better, prepared, way to do this. Does anyone know?
Currently I am just using the following method:
def is_backend_namespace? params[:controller].index("admin/") == 0 end
Thanks in advance
Arne