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