Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hook for method defined?

Tags:

ruby

I've been googling around for this and haven't been able to find an answer, which makes me think the answer is no, but I figured I'd ask here in case anyone knows for sure.

Does Ruby have a hook for when methods are defined (ie on a module or class)?

If not, is anyone familiar enough with the implementation of the main object to know how exactly it copies methods to Object when they're defined at the top level?

Really curious about this. Thanks for any info :)

like image 796
Andrew Avatar asked Jan 20 '18 02:01

Andrew


Video Answer


1 Answers

It does. Module#method_added https://ruby-doc.org/core-2.2.2/Module.html#method-i-method_added

module Thing
  def self.method_added(method_name)
    puts "Thing added #{method_name}"
  end
  def self.a_class_method; end
  def do_something; end
end

class Person
  def self.method_added(method_name)
    puts "I added #{method_name}"
  end
  attr_accessor :name 
end

Thing
Person.new 

# Thing added do_something
# I added name
# I added name=
like image 147
Josh Brody Avatar answered Oct 17 '22 09:10

Josh Brody