Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make get attr_accessor_with_default work with a collection?
    primarykey
    data
    text
    <p>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:</p> <pre><code>attr_accessor_with_default:weekly_magnitude_list, [0,0,0,0,0,0,0,0] </code></pre> <p>The above didn't do what I expected because all instances of the model end up sharing the same Array object. The blog (<a href="http://barelyenough.org/blog/2007/09/things-to-be-suspicious-of-attr_accessor_with_default-with-a-collection/" rel="nofollow noreferrer">http://barelyenough.org/blog/2007/09/things-to-be-suspicious-of-attr_accessor_with_default-with-a-collection/</a>) that clued me into that suggested a different syntax, basically wrapping the default value in a block.</p> <pre><code>attr_accessor_with_default(:weekly_magnitude_list) {[0,0,0,0,0,0,0,0]} </code></pre> <p>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. </p> <p>Does anybody know the correct way to do this?</p> <p>For your pleasure, I've included the output of a simple test demonstrating this:</p> <pre><code>class Container attr_accessor_with_default :naive_collection, [0,0] attr_accessor_with_default(:block_collection) {[0,0]} end &gt; c = Container.new =&gt; #&lt;Container:0x7f3610f717a8&gt; &gt; c.naive_collection[0] = "foo" =&gt; "foo" &gt; Container.new.naive_collection =&gt; ["foo", 0] # expected [0,0] &gt; c.block_collection[0] = "foo" =&gt; "foo" &gt; c.block_collection =&gt; [0, 0] # expected ["foo", 0] </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload