Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend an object in ruby with a module whose name is given in a parameter?

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.

like image 695
Peter Lewis Avatar asked Jul 03 '12 23:07

Peter Lewis


Video Answer


1 Answers

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.

like image 199
Peter Avatar answered Oct 24 '22 05:10

Peter