From: Thomas Coopman Date: 2006-07-24T05:36:38+09:00 Subject: Re: get caller of method ------=_Part_118393_3506534.1153686993873 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Thanks for the quick answer, I didn't think about do. I think I understand your explanation but I don't completly understand what eval does. I checked the documentation but I still don't really get it, could you explain it? Thomas On 7/23/06, Ashley Moran wrote: > > > On Jul 23, 2006, at 8:06 pm, thomas coopman wrote: > > > Hi, > > > > Does there exist a method to get the object or type of object that > > calls this method? > > > > for example: > > > > class Foo > > do > > end > > class Bar > > do > > end > > > > do > > if caller.kind_of?(Foo) > > puts "Foo" > > elsif caller.kind_of?(Bar) > > puts "Bar" > > end > > end > > > > Thanks! > > > > Thomas > > I'm assuming you meant something like: > > class Foo > def do_stuff > do_something > end > end > class Bar > def do_stuff > do_something > end > end > > def do_something > if caller.kind_of?(Foo) > puts "Foo" > elsif caller.kind_of?(Bar) > puts "Bar" > end > end > > since "do" is a reserved word in Ruby. > > In this case you can do the following: > > def do_something(b = binding) > case eval("self", b) > when Foo then "Called by Foo" > when Bar then "Bar told me to do it" > end > end > > Then you get: > Foo.new.do_stuff > => "Called by Foo" > > Bar.new.do_stuff > => "Bar told me to do it" > > Note however that it would be possible for a method to "lie" and pass > in another binding when the method is called. And also it won't work > in this case: > > class Foo > do_something > end > > because the calling object is an instance of Class, but you could use: > > def do_something(b = binding) > case eval("self.name", b) > when "Foo" then "Called when building Foo" > when "Bar" then "Bar's creator told me to do it" > end > end > > and you get: > class Foo > do_something > end > => "Called when building Foo" > > > Maybe there is a better way to do this but it's a starter for 10. > > > Ashley > > -- Thomas Coopman Thomas.coopman@gmail.com ------=_Part_118393_3506534.1153686993873--