0
0
Rubyprogramming~5 mins

Method_added hook in Ruby

Choose your learning style9 modes available
Introduction

The method_added hook lets you run code automatically whenever a new instance method is created in a class. It helps you watch or change methods as they appear.

You want to log or track every new method added to a class.
You want to automatically wrap or modify methods right after they are defined.
You want to enforce rules or validations on methods as they are created.
You want to create debugging tools that react to new methods.
You want to build frameworks that extend method behavior dynamically.
Syntax
Ruby
def self.method_added(method_name)
  # code to run when a new instance method is added
end

This hook is a class method and is called with the new method's name as a symbol.

Be careful to avoid infinite loops if you define methods inside method_added.

Examples
This example prints the name of each instance method added to MyClass. When greet is defined, it prints "Added method: greet".
Ruby
class MyClass
  def self.method_added(name)
    puts "Added method: #{name}"
  end

  def greet
    puts 'Hello!'
  end
end
Here, each time an instance method is added (foo and bar), the hook prints its name.
Ruby
class Example
  def self.method_added(name)
    puts "New method: #{name}"
  end

  def foo
    puts 'foo'
  end

  def bar
    puts 'bar'
  end
end
Sample Program

This program shows how method_added prints a message each time a new instance method is defined in the Tracker class. Then it calls the methods normally.

Ruby
class Tracker
  def self.method_added(method_name)
    puts "Method added: #{method_name}"
  end

  def hello
    puts 'Hi there!'
  end

  def bye
    puts 'Goodbye!'
  end
end

Tracker.new.hello
Tracker.new.bye
OutputSuccess
Important Notes

The method_added hook only works for instance methods, not class methods.

Defining methods inside method_added can cause infinite recursion, so use a guard variable if needed.

Summary

method_added runs automatically when a new instance method is defined.

It helps track or change methods as they appear in a class.

Use it carefully to avoid infinite loops.