views:

100

answers:

3

I'm hoping that Ruby's message-passing infrastructure means there's some clever trick for this...

How do I determine the calling object -- which object called the method I'm currently in?

+1  A: 

You mean like self?

irb> class Object
  ..   def test
  ..     self
  ..   end
  .. end
  => nil
irb> o = Object.new
  => #<Object:0xb76c5b6c>
irb> o.test
  => #<Object:0xb76c5b6c>
yjerem
++ Dude, that's totally awesome how that looks like a stylized Z
Pierreten
+2  A: 

You can easily look at the line of code that called the function of interest through

caller.first

which will tell you the filename and line number which called the relevant function. You could then back-calculate which object it was.

However, it sounds like you're more after some object that called a certain function, perhaps within an instance method. I'm not aware of a method for figuring this out - but I wouldn't use it anyway, since it seems to violate encapsulation badly.

Peter
That's a really good point, I will just pass the calling object instead. The idea was to simplify some of the arguments to a method by automatically reflecting some information about the calling object.
Joe
well, ideally, if it's more than once, it should be a method in a superclass, and you can use `self`.
Peter
+1  A: 

Technology at its finest:

 1  # phone.rb
 2  class Phone
 3    def caller_id
 4      caller
 5    end
 6  end
 7  
 8  class RecklessDriver
 9    def initialize
10      @phone = Phone.new
11    end
12    def dial
13      @phone.caller_id
14    end
15  end
16  
17  p = Phone.new
18  p.caller_id.inspect   # => ["phone.rb:18:in `<main>'"]
19  
20  macek = RecklessDriver.new
22  macek.dial.inspect    # => ["phone.rb:13:in `dial'", "phone.rb:22:in `<main>'"]

Note: Line number for demonstrative purposes. phone.rb:X refers to Line X of the script.

Look at phone.rb:13! This dial method is what sent the call! And phone.rb:22 refers to the reckless driver that used the dial method!

macek