从模块中获取类名
如何从模块中获取包含模块的类的类名?
module ActMethods def some_method(*attr_names) cls = self.class # this doesn't work end end
我怎么能进入cls变量加载这个模块的类的名称?
self.class
确实为您提供了调用该方法的对象的类。 假设模块包含在类中,这可以是包含模块或其子类的类。 如果您真的只想要名称,则可以使用self.class.name
。
如果您使用模块扩展了一个类并且想要获得该类,则可以执行cls = self
(如果您希望将类的名称作为字符串,则可以使用cls = name
)。
如果以上都没有帮助,您应该澄清您想要的内容。
如果由于某种原因self
不是一种选择,替代可能是ancestors
http://ruby-doc.org/core-2.0/Module.html#method-i-ancestors
# rails concern example: module Foo extend ActiveSupport::Concern included do p "Wooo hoo, it's #{top_ancestor_class}" end module ClassMethods def top_ancestor_class ancestors.first end end end class Event < ActiveRecord::Base include Foo end #=> Woo hoo, it's Event(....)
适合我。 正如塞普所说,你必须把它包括在内才能发挥作用。
module ActMethods def some_method(*attr_names) cls = self.class # this doesn't work puts cls end end class Boh include ActMethods end b = Boh.new b.some_method
PS:有关一般情况的答案,请参阅sepp2k的答案。
如果仅将模块包含在控制器中,则可能需要考虑使用controller_name.classify
来获取相应模型的名称。 例:
>> ArticlesController.controller_name.classify => "Article"
从那里你可以通过调用.constantize
上的.constantize
来获得实际的类(如果你想要的话)。