# Define method hook

**URL:** <https://www.ruby-forum.com/t/define-method-hook/114676>\
**Category:** Ruby\
**Created:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/define-method-hook/114676 "2007-09-17T13:24:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![brblakley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f14d63/32.png) [@brblakley](https://www.ruby-forum.com/u/brblakley)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/define-method-hook/114676/1 "2007-09-17T13:24:03Z")

</div>

Is there a way to intercept method defines, so that i can setup a  
callback whenever a new method is defined for a class? I’m looking  
for something that works with the def keyword, and doesn’t require  
any extensions.

-Ben

---

<div class="post-metadata">

**Author:** ![brblakley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f14d63/32.png) [@brblakley](https://www.ruby-forum.com/u/brblakley)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/define-method-hook/114676/2 "2007-09-17T13:24:03Z")

</div>

On 9/14/07, Ben B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Is there a way to intercept method defines, so that i can setup a  
> callback whenever a new method is defined for a class? I’m looking  
> for something that works with the def keyword, and doesn’t require  
> any extensions.

Yep. Module#method\_added  
If you do this:

class Example  
def self.method\_added(meth)  
p meth  
end  
end

After that, this code:  
class Example;def foo(baz);5;end;end

…will print out: :foo

---

<div class="post-metadata">

**Author:** ![brblakley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f14d63/32.png) [@brblakley](https://www.ruby-forum.com/u/brblakley)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/define-method-hook/114676/3 "2007-09-17T13:24:42Z")

</div>

> Is there a way to intercept method defines, so that i can setup a  
> callback whenever a new method is defined for a class?

class Module  
def method\_added(method\_name)  
p [caller[0], self, method\_name]  
end  
end

class Foo  
def bar  
end  
end

gegroet,  
Erik V.

---

<div class="post-metadata">

**Author:** ![brblakley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/f14d63/32.png) [@brblakley](https://www.ruby-forum.com/u/brblakley)\
**Post date:** [September 17, 2007, 1:25pm UTC](https://www.ruby-forum.com/t/define-method-hook/114676/4 "2007-09-17T13:25:15Z")

</div>

great, thanks.
