1

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?)

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

So would this print the name of each method that was added to a class where this was mixed in?
3

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.

Comments

0

If I understand your question correctly,

class_instance.send(method_name)

should do it

1 Comment

Isn't that just the equivalent of object.method() ? I'm looking to automatically cal a method every time I define a new method in a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.