rubysingletonevallocal-variableseigenclass

Add methods from modules to specific instances of a class dynamically


Here's the deal: I need to extend specifica instances of the class Box with some methods. The methods i need to include live inside modules and i want the Box instance to be able to include the modules dynamically. Now i am using a hook with an eval:

class Box
  def after_initialize
    if self.injected_module.present?
      eval("class << self; include #{self.injected_module}; end")
    end
  end
end

It is working quite well but i really feel dirty when i use eval. I'm looking for something like that:

module_to_inject = self.injected_module
self.eigenclass.class_eval do
   include module_to_inject
end

but i'm not being able to get the eigenclass to run class_eval on without monkeypatching the class like:

class Box; def eigenclass; class << self; self; end end end

Is there a beautiful (and reliable) way for me to do this?


Solution

  • All you need to add methods from modules to specific instances of Box dynamically is the Kernel#extend method:

    box.extend MyModule
    

    Also, because the verb "to inject" already has a meaning in Ruby from Enumerable#inject, the best verb for describing this is "to extend".