More methods at runtime

As I expected, I missed some stuff in my last post about adding methods at runtime. One thing is that the idiom for adding class methods is “class < < self" rather than "class << Classname"

More importantly, if you define things like I did in my last post, you will not be able to use variables in the method definition. The things after "class << self" are executed in a different scope that doesn't inherit the variables from the surrounding code.

Fortunately, Ola Bini has a post that explains some of these things in more detail. Obviously, the idiom for creating class methods at runtime uses a combination of “module_eval” and “define_method”:

class Test
  def self.makemethod(methodname)
    (class << self; self; end).module_eval do
      define_method(methodname) do |parameter|
        print("#{methodname} says #{parameter}")
      end
    end
  end
end

# Try it
Test.makemethod("hello")
Test.hello("world")
> hello says world