From 200548e45e42a2dfc2d9c3c6e56409e5c07c8706 Mon Sep 17 00:00:00 2001 From: Dylan Chong Date: Tue, 22 Jan 2019 14:58:58 +1300 Subject: [PATCH 1/2] Fixed documentation that implies the introduction of a mutability bug 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 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e4e98d6f..7a1b3b9e 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,7 @@ end class User include Virtus.model - attribute :info, Json, default: {} + attribute :info, Json, default: ->(_, _) { {} } end user = User.new From e7a82a93cddf9f38bf699397199734bccfcc633c Mon Sep 17 00:00:00 2001 From: Dylan Chong Date: Tue, 22 Jan 2019 15:01:02 +1300 Subject: [PATCH 2/2] Use lambda rather than proc for consistency with the rest of the readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a1b3b9e..73d2042e 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,7 @@ end class User include Virtus.model - attribute :info, Json, default: ->(_, _) { {} } + attribute :info, Json, default: lambda { |user, attribute| {} } end user = User.new