加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何在嵌套子模块中自动包含模块

发布时间:2020-12-17 02:14:54 所属栏目:百科 来源:网络整理
导读:我有一个模块Top,它有模块A和B.在每个模块中,我想使用模块C的类方法.为此,我必须为每个模块A和B包含C.是否可以包含C在Top中,所有子模块都可以访问它的类方法? 例: # I'll extend module C in example to make it shortermodule C def foo; puts 'Foo!' end
我有一个模块Top,它有模块A和B.在每个模块中,我想使用模块C的类方法.为此,我必须为每个模块A和B包含C.是否可以包含C在Top中,所有子模块都可以访问它的类方法?

例:

# I'll extend module C in example to make it shorter

module C
  def foo; puts 'Foo!' end
end

module Top
  extend C

  module A  end
  module B  end
end

# That's how it works now

Top.foo
#=> "Foo!"
Top::A.foo
#=> NoMethodError: undefined method `foo' for Top::A:Module
Top::B.foo
#=> NoMethodError: undefined method `foo' for Top::B:Module

# That's how I want it to work

Top.foo
#=> "Foo!"
Top::A.foo
#=> "Foo!"
Top::B.foo
#=> "Foo!"

解决方法

实际上它是可能的
OP更新了代码,所以这是我的实现:

class Module
  def submodules
    constants.collect {|const_name| const_get(const_name)}.select {|const| const.class == Module}
  end
end


module C
  # this gets called when the module extends another class or module
  # luckily it does _not_ get called when we extend via :send
  def self.extended(base)
    # collect all submodules and extend them with self
    base.submodules.each{|m| m.send :extend,self }
  end
  def c1
    puts "c1"
  end
end

module Top
  module A;end
  module B;end
  # extend needs to go at the end - otherwise Top doesnt know about its submodules
  extend C
end

Top.c1     # => "c1"
Top::A.c1  # => "c1"
Top::B.c1  # => "c1"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读