I want to give one of my models an attribute accessor that defaults to an array of eight zeros. This is the first syntax I tried:
attr_accessor_with_default:weekly_magnitude_list, [0,0,0,0,0,0,0,0]
The above didn't do what I expected because all instances of the model end up sharing the same Array object. The blog (http://barelyenough.org/blog/2007/09/things-to-be-suspicious-of-attr_accessor_with_default-with-a-collection/) that clued me into that suggested a different syntax, basically wrapping the default value in a block.
attr_accessor_with_default(:weekly_magnitude_list) {[0,0,0,0,0,0,0,0]}
That doesn't work (for me, in Rails 3). Any time I call the accessor, I seem to be getting a completely new Array object. That effectively means I can't write to it.
Does anybody know the correct way to do this?
For your pleasure, I've included the output of a simple test demonstrating this:
class Container
attr_accessor_with_default :naive_collection, [0,0]
attr_accessor_with_default(:block_collection) {[0,0]}
end
> c = Container.new
=> #<Container:0x7f3610f717a8>
> c.naive_collection[0] = "foo"
=> "foo"
> Container.new.naive_collection
=> ["foo", 0]
# expected [0,0]
> c.block_collection[0] = "foo"
=> "foo"
> c.block_collection
=> [0, 0]
# expected ["foo", 0]