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
Posted by Dragos Miron to HouseTrip Deck (2012-11-27 16:12)