On Jan 21, 2011, at 3:41 PM, Nick Sutterer wrote:

> By accident I solved this with a 10-liner months ago, why not use
> something like that? 
> https://github.com/apotonick/hooks/blob/master/lib/hooks/inheritable_attribute.rb
> 
> It's simple, clean and does exactly what you expect.
> 

Well, as long as "what you expect" doesn't involve keeping anything more 
complicated than a flat Hash/Array/etc in the class variable:

irb --> a = { :key_1 => 1, :key_2 => ['x','y'] }
    ==> {:key_1=>1, :key_2=>["x", "y"]}

irb --> b = a.clone
    ==> {:key_1=>1, :key_2=>["x", "y"]}

irb --> b[:key_2] << 'z'
    ==> ["x", "y", "z"]

irb --> a
    ==> {:key_1=>1, :key_2=>["x", "y", "z"]}

Object#clone solves the problems caused when you add a key to hash b in this 
example, but it doesn't completely separate the objects. This code does:

totally_cloned = Marshal.load(Marshal.dump(source))

but that's fairly inefficient and fails disastrously if an object that can't be 
marshalled is involved (Procs, for instance).

I can't really decide whether doing the clone causes results that are more or 
less surprising than the existing version.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to