solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

Fixed documentation that implies the introduction of a mutability bug #394

Open dylan-chong opened 5 years ago

dylan-chong commented 5 years ago

Setting the default value to a hash (or empty array, or any other mutable object) can cause mutability/side-effect problems to be introduced. These are very hard and time-consuming to track down.

For example:

u1 = User.new
u1.info[:something] = 1

u2 = User.new
u2.info[:something] # => 1

In the above example, one would expect u2.info[:something] to return nil, however because the default value Hash is shared between all users, u2.info[:something] returns 1.

Using the lambda means that a new Hash will be created each time a new user is created, avoiding the above side-effect issue:

u1 = User.new
u1.info[:something] = 1

u2 = User.new
u2.info[:something] # => nil