【问题标题】:How to automatically include module in nested submodules如何在嵌套子模块中自动包含模块
【发布时间】:2012-12-19 07:44:35
【问题描述】:

我有一个模块Top,它有模块AB。在它们中的每一个中,我都想使用模块C 的类方法。为此,我必须为每个模块 AB 包含 C。是否可以在Top 中包含C,以便所有子模块都可以访问其类方法?

例子:

# 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!"

【问题讨论】:

  • 显示代码结构,问题会更容易理解。
  • 您可以让AB 继承自Z,并将C 包含到Z

标签: ruby namespaces


【解决方案1】:

其实是可以的
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"

【讨论】:

    【解决方案2】:

    没有内置的方式。你必须像这样实现它:

    class Module
      def extend_each_module m
        constants.each do |sym|
          const_get(sym).instance_eval{extend(m) if kind_of?(Module)}
        end
      end
    end
    
    module C
      def foo
        puts "Foo!"
      end
    end
    
    module Top
      module A; end
      module B; end
      extend C
      extend_each_module C
    end
    
    Top.foo
    # => Foo!
    Top::A.foo
    # => Foo!
    Top::B.foo
    # => Foo!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2015-03-22
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多