# Find where in hierarchy was the message handled

**URL:** <https://www.ruby-forum.com/t/find-where-in-hierarchy-was-the-message-handled/87563>\
**Category:** Ruby\
**Created:** [March 3, 2007, 11:22pm UTC](https://www.ruby-forum.com/t/find-where-in-hierarchy-was-the-message-handled/87563 "2007-03-03T23:22:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nasir\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/838e76/32.png) [@Nasir\_K](https://www.ruby-forum.com/u/Nasir_K)\
**Post date:** [March 3, 2007, 11:22pm UTC](https://www.ruby-forum.com/t/find-where-in-hierarchy-was-the-message-handled/87563/1 "2007-03-03T23:22:56Z")

</div>

If you have an hieararchy of classes and the parent class method has a  
complex dispatch logic to the children then you may like to test if the  
dispatch happens correctly or not.

Here is an example -  
I have many types of audio players and there is a base player doing some  
common stuff.

#— file players.rb -------  
class BasePlayer  
def play  
# do base players job  
end  
end

class Mp3Player \< BasePlayer  
def play  
# play mp3 files  
end  
end  
#--------------------------

I oftentimes in my test want to know if the base class’s or derived  
class’s  
play method was invoked. This example may not be enough to convince you  
of  
the requirement but I do have use cases in which I want to know where in  
hierarchy was the method handled. So I have this test with associated  
wrapper module.

#-----file tc\_players.rb----------

require ‘test/unit’  
require ‘players’

class PlayerTestCase \< Test::Unit::TestCase

def setup  
@b = BasePlayer.new  
@m = Mp3Player.new  
end

def test\_play  
@b.extend(PlayerExtender)  
@m.extend(PlayerExtender)  
assert\_equal( “BasePlayer”, @b.play[0] )  
assert\_equal( “Mp3Player”, @m.play[0] )  
end

end

module PlayerExtender

def PlayerExtender.extended(xtendee)  
xtendee.class.instance\_methods(false).each do |m|  
PlayerExtender.wrap\_method(xtendee.class, m)  
end  
end

def PlayerExtender.wrap\_method(klass, meth)  
klass.class\_eval do  
alias\_method “old\_#{meth}”, “#{meth}”  
define\_method(meth) do |\*args|  
[self.class.name, self.send(“old\_#{meth}”,\*args)]  
end  
end  
end  
end

#-------------------------

I am posting this here for two reasons.

(a) Please let me know if this can be improved or I have overlooked a  
simpler solution  
(b) In the hope that this could be useful to others.

Thanks
