【问题标题】:Can a module class method be called from a class nested in that module?可以从嵌套在该模块中的类调用模块类方法吗?
【发布时间】:2016-06-15 20:47:00
【问题描述】:

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

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

我知道我可以通过使用直接在A 上调用foo

def self.bar
  A.foo
end

但理想情况下,如果可能的话,我希望有一种方法让A 成为B 的祖先链的一部分。任何提示将不胜感激。

【问题讨论】:

  • 可能没有办法绕过它,尝试使用类而不是模块。

标签: ruby-on-rails ruby oop


【解决方案1】:

我不知道有一种直接的方法可以完全按照您的要求进行操作。但是您可以将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】:

    使用ActiveSupport(如果您使用 Rails,您已经拥有它),您可以执行以下操作:

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

    关于变形器的更多信息:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2015-09-15
      • 2015-07-11
      • 2011-09-05
      • 2018-03-26
      相关资源
      最近更新 更多