attr_accessor_with_default with collections #885

Closed
lighthouse-import opened this Issue May 16, 2011 · 2 comments

Comments

Projects
None yet
1 participant

Imported from Lighthouse. Original ticket at: http://rails.lighthouseapp.com/projects/8994/tickets/6496
Created by parrish - 2011-03-01 19:14:49 UTC

I started digging into this when I stumbled across this SO question: http://stackoverflow.com/questions/3481406
To give an example of the unexpected behavior:

class Container
  attr_accessor_with_default :foo, [0, 0]
end

# This works as expected
c = Container.new
c.foo = ["foo", "bar"]  # => ["foo", "bar"]
Container.new.foo       # => [0, 0]
c.foo[0] = 0            # => [0, "bar"]
Container.new.foo       # => [0, 0]

# This changes the class default value
c2 = Container.new
c2.foo                  # => [0, 0]
c2.foo[0] = "problem!"  # => ["problem!", 0]
Container.new.foo       # => ["problem!", 0]

I'll be submitting a patch shortly.

Imported from Lighthouse.
Comment by parrish - 2011-03-01 19:24:52 UTC

I'm sure there is a more elegant approach to this, but I couldn't think of a simpler one that maintained scopes correctly.
Refactoring suggestions are welcome :)

Discarding the block option would definitely clarify the intent and code in this method, but that's just my two cents.

Attachments saved to Gist: http://gist.github.com/971794

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment