Rails 3: Get current namespace?

2020-06-30 09:22发布

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

8条回答
来,给爷笑一个
2楼-- · 2020-06-30 09:28

You can use:

self.class.parent == Admin
查看更多
Rolldiameter
3楼-- · 2020-06-30 09:29

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"
查看更多
甜甜的少女心
4楼-- · 2020-06-30 09:29

Setting the namespace in application controller:

path = self.controller_path.split('/')
@namespace = path.second ? path.first : nil
查看更多
祖国的老花朵
5楼-- · 2020-06-30 09:29

In Rails 6, the controller class does not seem to have a namespace method on it.

The solution that seemed cleanest and worked for me in a view was: controller.class.module_parent

Specifically, if your namespace is Admin:: and you wanted 'admin', you'd do: controller.class.module_parent.to_s.downcase

查看更多
欢心
6楼-- · 2020-06-30 09:33

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
查看更多
Viruses.
7楼-- · 2020-06-30 09:35

In both the controller and the views, you can parse controller_path, eg.:

namespace = controller_path.split('/').first
查看更多
登录 后发表回答