Alex Rivera | Logout

Add ruby class methods or instance methods dynamically

Asked 2011-09-12T18:57:23.770
12

I am quite new to Ruby, so still learning. I was researching quite a bit about how to add methods dynamically, and I was successful to create instance methods, but not successful when creating class methods.

This is how I generated instance methods:

  class B
    def before_method
      puts "before method"
    end

    def self.run(method)
        send :define_method, method do
          before_method
          puts "method #{method}"
        end
    end
  end

  class A < B
    run :m
    run :n
  end

Any idea about the best ways to create static methods?

My final task is to look for the best way to create "before" and "after" tasks for class methods.

Edit
Report

1 Answer

2

Here's something re-worked to use class methods:

class B
   def self.before_method
     puts "before method"
   end

  def self.run(method)
    define_singleton_method(method) do
      before_method
      puts "method #{method}"
    end
  end
end

Update: Using define_singleton_method from Ruby 1.9 which properly assigns to the eigenclass.

answered 2011-09-12T19:07:04.267

Your Answer