Ruby: Include a dynamic module name

I'm doing a similar thing. I found this answer useful: How to convert a string to a constant in Ruby?

Turns out I was looking for the constantize method. This is the line I'm using in my code:

include "ModuleName::#{var.attr}".constantize

Edit:

So ack, I ran into various problems with actually using that line myself. Partially because I was trying to call it inside a method in a class. But since I'm only calling one method in the class (which calls/runs everything else) the final working version I have now is

"ModuleName::#{var.attr}".constantize.new.methodname

Obviously methodname is an instance method, so you could get rid of the new if yours is a class method.


Include is a method on a class.

If you want to call it inside a model, you need to execute the code in the context of its singleton class.

p =  self.user.company.subdomain + ".rb"
if File.exists?(Rails.root + "lib/" + p)
myself = self
class_eval do
  include self.const_get(myself.user.company.subdomain.capitalize.to_sym)
end
self.custom_add_url

EDIT:

class << self doesn't accept a block; class_eval does, hence it preserves the state of local variables. I've modified my solution to use it.