如何在下面的过滤器中找到名称空间或模块"Foo"的名称?
class ApplicationController < ActionController::Base
def get_module_name
@module_name = ???
end
end
class Foo::BarController < ApplicationController
before_filter :get_module_name
end
如何在下面的过滤器中找到名称空间或模块"Foo"的名称?
class ApplicationController < ActionController::Base
def get_module_name
@module_name = ???
end
end
class Foo::BarController < ApplicationController
before_filter :get_module_name
end
这些解决方案中没有一个考虑多个父模块的常数.例如:
A::B::C
从Rails 3.2开始.你可以简单地:
"A::B::C".deconstantize #=> "A::B"
从Rails 3.1开始.你可以:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )
这是因为#解调是#解构的对立面:
"A::B::C".demodulize #=> "C"
如果确实需要手动执行此操作,请try 以下操作:
constant_name = "A::B::C"
constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]