Rails 3: Get current namespace?

删除回忆录丶 提交于 2019-12-03 22:06:31

You can use:

self.class.parent == Admin

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

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

namespace = controller_path.split('/').first

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"

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]

Setting the namespace in application controller:

path = self.controller_path.split('/')
@namespace = path.second ? path.first : nil
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!