从模块中获取类名

ast*_*nic 17 ruby inheritance

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

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

我怎么能进入cls变量加载这个模块的类的名称?

sep*_*p2k 10

self.class确实为您提供了调用该方法的对象的类.假设模块包含在类中,这可以是包含模块的类或其子类.如果你真的只想要这个名字,你可以self.class.name改用它.

如果您使用模块扩展了一个类并且想要获取该类,则可以这样做cls = self(或者cls = name如果您希望将该类的名称作为字符串).

如果以上都没有帮助,您应该澄清您想要的内容.


equ*_*nt8 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(....)
Run Code Online (Sandbox Code Playgroud)