I would like to extend a Ruby object with a module, but I want to be able to change which module to use at runtime, and have the ability to vary this by object. In other words, I'd like to pass the name of the module to extend as a paramter. 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 that the method get_module_name_from_config_file returns a String with the desired module's name - here either "M1" or "M2".)
But I get this:
error: wrong argument type String (expected Module).
because m is of type String, not Module, obviously. I tried it with m being a symbol too, but I get the same problem (replace String with Symbol in the error message).
So, can I convert m into something of type Module? Or is there another way I can achieve this?
Thanks in advance.
You can do it like this (modified to use const_get per Jörg W Mittag's suggestion)
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
You had some errors in your code above, btw - class and module should be lowercase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With