On 11/2/06, Rob Biedenharn <Rob / agileconsultingllc.com> wrote:
> Why is this so hard to understand?  Rails isn't really doing anything
> magic or really even tricky here -- just "unexpected".
>
> You are just confusing references and objects.
>
>  >> require 'ostruct'
> => true
>  >> o = OpenStruct.new('page' => "original", 'cover' => "hard")
> => #<OpenStruct cover="hard", page="original">
>  >> p = o.page
> => "original"
>
> No surprise there.  Let's change the contents of the page.
>
>  >> o.page.replace("forgery")
> => "forgery"
>
> ...and check in with our variable (aka, object reference):
>
>  >> p
> => "forgery"
>
> Yup. Still refers to the same String object as o.page.  Now let's do
> an assignment:
>
>  >> o.page = "restoration"
> => "restoration"
>  >> p
> => "forgery"
>
> o.page now refers to a new object.  But o.page = "restoration" is
> really just sugar for o.page=("restoration"), right?
>
>  >> def o.page=(kind); self.page.replace(kind); end
> => nil

This is the issue.  I understand how assignment methods work, really I
do =).  I just don't see a reason for this and would assume the
implementation is the simplest thing unless we _really_ need to change
that object in place.  I would normally think this is just an
assignment, unless there were good optimization reasons to do
otherwise.

def o.page=(str); self.page = str; end

# or more typically w/i the class def somewhere

attr_accessor :page
def initialize
   @page = nil
end

Not sure why Rails would do an .replace instead, but maybe there are
good performance reasons  relating to ActiveRecord...

- Rob

-- 
http://www.robsanheim.com
http://www.seekingalpha.com
http://www.ajaxian.com