mareiou
mareiou

Reputation: 414

How to extend a module on a class dynamically?

I currently have two classes with each extending a different module:

class Example1
  def initialize
    extend TopModule:SubModule1
  end
end

class Example2
  def initialize
    extend TopModule:SubModule2
  end
end

Instead of having two classes with each its own module extended, is it possible to create a single class and then extend the module at the object level?

I have added the name of the module and passing that to the constructor of the object but complains with the code.

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>

Overall problem: Let's say I have N objects (they all should come from the same class BUT each object must have it's own module). What would be the best approach to have this capability?

Upvotes: 0

Views: 679

Answers (2)

Ted Price
Ted Price

Reputation: 76

Updated answer!

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

Upvotes: 4

marmeladze
marmeladze

Reputation: 6564

You are possibly on wrong way, and that forces you to find an "ungood" solution. But here it is.

class Example
  def initialize m
    self.instance_eval("extend Topmodule::#{m}")
  end
end

Upvotes: 0

Related Questions