模块类方法可以从嵌套在该模块中的类中调用吗?

时间:2021-09-06 16:04:57

Is it possible to call a module's class method from a nested class method? For instance, if I had:

是否可以从嵌套类方法调用模块的类方法?例如,如果我有:

module A
  def self.foo
    'hello'
  end
end

module A
  class B
    def self.bar
      foo # Fails since A is not in B's ancestor chain
    end
  end
end

I know that I can call foo directly on A by using

我知道我可以用

def self.bar
  A.foo
end

But ideally I would like a way to have A be part of B's ancestor chain if possible. Any tips would be appreciated.

但理想情况下,如果可能的话,我想要一种方法,让a成为B的祖先链的一部分。任何提示都可以。

2 个解决方案

#1


3  

I'm not aware of a straightforward way to do exactly what you're asking. But you can move A's self methods to instance methods in another module and have B extend that module:

我不知道有什么直接的方法来做你想要的。但是你可以把A的self方法移到另一个模块的实例方法中,让B扩展那个模块:

module A
  module ClassMethods
    def foo
      'hello'
    end
  end
  extend ClassMethods
end

module A
  class B
    extend A::ClassMethods

    def self.bar
      foo
    end
  end
end

#2


1  

With ActiveSupport (you already have it if you use Rails) you can do something like this:

使用ActiveSupport(如果你使用Rails,你已经有了),你可以做以下事情:

def self.bar
  self.to_s.deconstantize.constantize.foo
end

More about inflectors:

更多关于弯曲物:

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

#1


3  

I'm not aware of a straightforward way to do exactly what you're asking. But you can move A's self methods to instance methods in another module and have B extend that module:

我不知道有什么直接的方法来做你想要的。但是你可以把A的self方法移到另一个模块的实例方法中,让B扩展那个模块:

module A
  module ClassMethods
    def foo
      'hello'
    end
  end
  extend ClassMethods
end

module A
  class B
    extend A::ClassMethods

    def self.bar
      foo
    end
  end
end

#2


1  

With ActiveSupport (you already have it if you use Rails) you can do something like this:

使用ActiveSupport(如果你使用Rails,你已经有了),你可以做以下事情:

def self.bar
  self.to_s.deconstantize.constantize.foo
end

More about inflectors:

更多关于弯曲物:

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html