Posted over 8 years ago. Visible to the public.

has_defaults issues

What
The object returned by has_defaults apparently is the same between multiple object creations.
Consider this scenario:

Copy
class Order has_defaults :items => [] end o1 = Order.new o1.items #=>> [] o1.items << item o1.items #=>> [item] o2 = Order.new o2.items #=>> [item]

So, now o2.items is not empty by default because we modified the same object in has_defaults

How
When using has_defaults on a model, consider using it in the following way:

Copy
has_defaults :items => proc {[] }

When
Consider doing this when the object you want as default might not be substituted (keeping the same reference)

Example:
Array: [1,2] << 2
String: "Hello" << "World"

As long as you change the object from has_defaults with a new one, you don't need to do this

Owner of this card:

Avatar
Dragos Miron
Last edit:
about 6 years ago
by dncrht
Tags:
defaults, has_defaults
Posted by Dragos Miron to HouseTrip Deck
This website uses short-lived cookies to improve usability.
Accept or learn more