从模块中获取类名

时间:2009-11-28 14:16:46

标签: ruby inheritance

如何从模块中获取包含模块的类的类名?

module ActMethods
  def some_method(*attr_names)
    cls = self.class # this doesn't work 
  end
end

如何进入cls变量,加载此模块的类的名称?

4 个答案:

答案 0 :(得分:10)

self.class会为您提供调用该方法的对象的类。假设模块包含在类中,这可以是包含模块的类或其子类。如果您真的只想要名称,可以使用self.class.name代替。

如果您使用模块扩展了一个类并且想要获得该类,那么只需要cls = self(或cls = name,如果您希望将该类的名称作为字符串)。

如果以上都没有帮助,你应该澄清你想要的东西。

答案 1 :(得分:7)

如果出于某种原因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(....)

答案 2 :(得分:1)

适合我。正如塞普所说,你必须把它包括起来才能发挥作用。

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

答案 3 :(得分:1)

PS: For the general case answer, see sepp2k's answer.

If you included the module in controllers only, you might want to consider using controller_name.classify to get the name of the corresponding model. Example:

>> ArticlesController.controller_name.classify
=> "Article"

From there you could get the actual class (if you want), by calling .constantize on the result.