Roman A. Taycher
Roman A. Taycher

Reputation: 19505

ruby - is there a way to add code to run after each method definition

I understand that def is a keyword and can't be overridden.

But is there a way to call a method when a method gets registered with a class(passing in the name of the method being created?)

Upvotes: 1

Views: 178

Answers (3)

Sławosz
Sławosz

Reputation: 11707

To create a mixin with that hook:

module Foo
  def method_added(method_name)
    puts "method #{method_name} added"
  end
end

class Bar
  extend Foo

  def some_method
  end
end

Notice that method_added is class method (strictly class Class instance instance method sic!), since it is defined in Module class. So we have to add it with extend so it goes to Bar metaclass.

Upvotes: 3

Jörg W Mittag
Jörg W Mittag

Reputation: 369594

That's what the Module#method_added hook method is for:

module Foo
  def self.method_added(meth)
    p meth
  end

  def bar; end
end

# :bar

Upvotes: 7

Despo
Despo

Reputation: 191

If I understand your question correctly,

class_instance.send(method_name)

should do it

Upvotes: 0

Related Questions