可以从嵌套在该模块中的类中调用模块类方法吗? [英] Can a module class method be called from a class nested in that module?

查看:62
本文介绍了可以从嵌套在该模块中的类中调用模块类方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我知道我可以使用

def self.bar
  A.foo
end

直接在A上调用foo

def self.bar
  A.foo
end

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

解决方案

我不知道一种完全按照您的要求进行操作的简单方法.但是您可以将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

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.

解决方案

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:

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

这篇关于可以从嵌套在该模块中的类中调用模块类方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆