title: get object at end of method chain in ruby
body: <h2><strong>EDITED</strong></h2>
  
  <p>Suppose I have the following code:</p>
  
  <pre><code>class Kid &lt; ActiveRecord::Base
    has_one :calculator
    attr_accessible :favorite_num
  end
  
  class Teacher &lt; ActiveRecord::Base
    has_one :calculator
    # does not have a favorite_num
  end
  
  class Calculator &lt; ActiveRecord::Base
    belongs_to :kid
    belongs_to :teacher
  
    def compute(number)
      # takes the number passed in and multiplies it by
      # the favorite_num if it exists, otherwise returns 42
    end
  end
  </code></pre>
  
  <p>What I need to be able to do is define <code>compute</code> above so that calls like the following work.</p>
  
  <pre><code>kid = Kid.first
  =&gt; #&lt;User id: 1, favorite_num: 4, . . . &gt;
  kid.calculator.compute(5)
  =&gt; 20
  teacher = Teacher.first
  =&gt; #&lt;Teacher id: 1, . . . &gt;
  teacher.calculator.compute(5)
  =&gt; 42
  </code></pre>
  
  <p>Some additional constraints:</p>
  
  <ul>
  <li>I don't want to put a <code>compute</code> method in both the <code>Kid</code> and <code>Teacher</code> classes. This is because:
  <ul>
  <li>I want to keep things as dry as possible, and objects of several other classes have <code>Calculators</code> associated with them as well</li>
  <li>doing so would require massive refactoring of the legacy code I'm working with (there are many <code>calculator.compute</code> calls scattered around the code, often invoked in less-than obvious ways)</li>
  </ul></li>
  </ul>
  
  <p><strong>ORIGINAL VERSION</strong></p>
  
  <p>If I have</p>
  
  <pre><code>object.foo
  </code></pre>
  
  <p>then the value of <code>self</code> in the context of <code>foo</code> is <code>object</code>. But what if I have: </p>
  
  <pre><code>object.foo.bar
  </code></pre>
  
  <p>How can I refer to <code>object</code> from within the definition of <code>bar</code>? <code>self</code> obviously won't work, since it just equals the return value of <code>object.foo</code>.</p>
  
  <p>I cannot change the implementation of <code>foo</code>. And <code>foo</code> and <code>bar</code> cannot be called on objects of the same class.</p>