首页 > 解决方案 > 如何动态扩展类上的模块?

问题描述

我目前有两个类,每个类扩展一个不同的模块:

class Example1
  def initialize
    extend TopModule:SubModule1
  end
end

class Example2
  def initialize
    extend TopModule:SubModule2
  end
end

是否可以创建一个类然后在对象级别扩展模块,而不是让两个类都扩展自己的模块?

我已经添加了模块的名称并将其传递给对象的构造函数,但抱怨代码。

class Example
  def initialize (module)
    self.send("extend TopModule::#{module}"
  end
end

object = Example.new('Submodule1')

NoMethodError:
  undefined method `extend TopModule::SubModule1' for #<Example:0x00000000057c8198>

总体问题:假设我有 N 个对象(它们都应该来自同一个类,但每个对象都必须有自己的模块)。拥有这种能力的最佳方法是什么?

标签: ruby

解决方案


更新答案!

module TopModule
  module SubModule1
    def hello
      puts "Hello from #1"
    end
  end
end

module TopModule
  module SubModule2
    def hello
      puts "Hello from #2"
    end
  end
end

class Example
  def initialize(mod)
    extend TopModule.const_get(mod)
  end
end

Example.new("SubModule1").hello
# => Hello from #1
Example.new("SubModule2").hello
# => Hello from #2

推荐阅读