has_defaults issues

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

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:

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

Dragos Miron over 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more