How can I extend an object in ruby ​​using the module whose name is specified in the parameter?

I would like to extend the Ruby object with a module, but I want to be able to change which module to use at runtime, and to be able to change this by object. In other words, I would like to pass the module name extendas a parameter. How can i do this?

I tried the following:

module M1
end

module M2
end

class C
  def initialize module_to_use
    extend module_to_use
  end
end

m = get_module_name_from_config_file
c1 = C.new m

(Assuming the method get_module_name_from_config_filereturns a Stringwith the desired module name - here either "M1", or "M2".)

But I get this:

error: wrong argument type String (expected Module).

because it mhas a type String, and not Module, obviously. I tried this with a character m, but I get the same problem (replace Stringwith Symbolin the error message).

, m Module? ?

.

+5
1

(, const_get JΓΆrg W Mittag)

module M1
end

module M2
end

class C
  def initialize module_to_use
    extend module_to_use
  end
end

m = Module::const_get("M1")
c1 = C.new m

, btw - class module .

+5

All Articles