如何在Ruby on Rails中以编程方式找到名称空间/模块名称? [英] How do you find the namespace/module name programmatically in Ruby on Rails?
本文介绍了如何在Ruby on Rails中以编程方式找到名称空间/模块名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在下面的过滤器中找到名称空间或模块"Foo"的名称?
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
推荐答案
这些解决方案均未考虑具有多个父模块的常量.例如:
None of these solutions consider a constant with multiple parent modules. For instance:
A::B::C
从Rails 3.2.x开始,您可以简单地:
As of Rails 3.2.x you can simply:
"A::B::C".deconstantize #=> "A::B"
从Rails 3.1.x开始,您可以:
As of Rails 3.1.x you can:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )
这是因为#demodulize与#deconstantize相反:
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]
这篇关于如何在Ruby on Rails中以编程方式找到名称空间/模块名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文