Ste*_*pes 55 ruby namespaces ruby-on-rails
如何在下面的过滤器中找到命名空间或模块"Foo"的名称?
class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = ???
  end
end
class Foo::BarController < ApplicationController
  before_filter :get_module_name
end
Jas*_*son 98
这些解决方案都没有考虑具有多个父模块的常量.例如:
A::B::C
从Rails 3.2.x开始,您可以简单地:
"A::B::C".deconstantize #=> "A::B"
从Rails 3.1.x开始,您可以:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )
这是因为#demodulize与#deconstantize相反:
"A::B::C".demodulize #=> "C"
如果您确实需要手动执行此操作,请尝试以下操作:
constant_name = "A::B::C"
constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]
Dan*_*aft 22
这应该这样做:
  def get_module_name
    @module_name = self.class.to_s.split("::").first
  end
如果控制器确实有模块名称,这将有效,但如果没有,则返回控制器名称.
class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = self.class.name.split("::").first
  end
end
但是,如果我们将此更改为:
class ApplicatioNController < ActionController::Base
  def get_module_name
    my_class_name = self.class.name
    if my_class_name.index("::").nil? then
      @module_name = nil
    else
      @module_name = my_class_name.split("::").first
    end
  end
end
您可以确定该类是否具有模块名称,并返回除您可以测试的类名以外的其他内容.
self.class.module_parent
Hettomei 的答案在 Rails 6.0 之前都可以正常工作
弃用警告:
Module#parent已重命名为module_parent.parent已弃用,将在 Rails 6.1 中删除。
| 归档时间: | 
 | 
| 查看次数: | 44215 次 | 
| 最近记录: |