From 72d969260fadea6047a29eb00099b8e88f689fb9 Mon Sep 17 00:00:00 2001 From: Michael Herold Date: Sun, 30 Sep 2018 21:21:55 -0500 Subject: Prevent deep_merge from mutating nested hashes The `DeepMerge` extension has two methods of mutating hashes: a destructive one and a non-destructive one. The `#deep_merge` version should not mutate the original hash or any hash nested within it. The `#deep_merge!` version is free to mutate the receiver. Without deeply duplicating the values contained within the hash, the invariant of immutability cannot be held for the original hash. In order to preserve that invariant, we need to introduce a method of deeply duplicating the hash. The trick here is that we cannot rely on a simple call to `Object#dup`. Some classes within the Ruby standard library are not duplicable in particular versions of Ruby. Newer versions of Ruby allow these classes to be "duplicated" in a way that returns the original value. These classes represent value objects, so it is safe to return the original value ... unless the classes are monkey-patched, but that isn't something we can protect against. This implementation does a best-effort to deeply duplicate an entire hash by relying on these value object classes being able to return themselves without violating immutability. --- lib/hashie/utils.rb | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'lib/hashie/utils.rb') diff --git a/lib/hashie/utils.rb b/lib/hashie/utils.rb index d8e05fe..5b55b9a 100644 --- a/lib/hashie/utils.rb +++ b/lib/hashie/utils.rb @@ -12,5 +12,33 @@ module Hashie "defined in #{bound_method.owner}" end end + + # Duplicates a value or returns the value when it is not duplicable + # + # @api public + # + # @param value [Object] the value to safely duplicate + # @return [Object] the duplicated value + def self.safe_dup(value) + case value + when Complex, FalseClass, NilClass, Rational, Method, Symbol, TrueClass, *integer_classes + value + else + value.dup + end + end + + # Lists the classes Ruby uses for integers + # + # @api private + # @return [Array] + def self.integer_classes + @integer_classes ||= + if const_defined?(:Fixnum) + [Fixnum, Bignum] # rubocop:disable Lint/UnifiedInteger + else + [Integer] + end + end end end -- cgit v1.2.1