Sha256: 2b48a47839b285a6c0b56b65657313b79104a95b4809b654eae8f4299a5bb888

Contents?: true

Size: 1.19 KB

Versions: 50

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

# Copied from active support
# @see active_support/core_ext/object/duplicable.rb

require 'active_support_ext/object/duplicable'

class Object
  # Returns a deep copy of object if it's duplicable. If it's
  # not duplicable, returns +self+.
  #
  #   object = Object.new
  #   dup    = object.deep_dup
  #   dup.instance_variable_set(:@a, 1)
  #
  #   object.instance_variable_defined?(:@a) # => false
  #   dup.instance_variable_defined?(:@a)    # => true
  def deep_dup
    duplicable? ? dup : self
  end
end

class Array
  # Returns a deep copy of array.
  #
  #   array = [1, [2, 3]]
  #   dup   = array.deep_dup
  #   dup[1][2] = 4
  #
  #   array[1][2] # => nil
  #   dup[1][2]   # => 4
  def deep_dup
    map(&:deep_dup)
  end
end

class Hash
  # Returns a deep copy of hash.
  #
  #   hash = { a: { b: 'b' } }
  #   dup  = hash.deep_dup
  #   dup[:a][:c] = 'c'
  #
  #   hash[:a][:c] # => nil
  #   dup[:a][:c]  # => "c"
  def deep_dup
    hash = dup
    each_pair do |key, value|
      if key.frozen? && key.is_a?(::String)
        hash[key] = value.deep_dup
      else
        hash.delete(key)
        hash[key.deep_dup] = value.deep_dup
      end
    end
    hash
  end
end

Version data entries

50 entries across 50 versions & 1 rubygems

Version Path
grover-1.2.1 lib/active_support_ext/object/deep_dup.rb
grover-1.2.0 lib/active_support_ext/object/deep_dup.rb
grover-1.1.11 lib/active_support_ext/object/deep_dup.rb
grover-1.1.10 lib/active_support_ext/object/deep_dup.rb
grover-1.1.9 lib/active_support_ext/object/deep_dup.rb
grover-1.1.8 lib/active_support_ext/object/deep_dup.rb
grover-1.1.7 lib/active_support_ext/object/deep_dup.rb
grover-1.1.6 lib/active_support_ext/object/deep_dup.rb
grover-1.1.5 lib/active_support_ext/object/deep_dup.rb
grover-1.1.4 lib/active_support_ext/object/deep_dup.rb
grover-1.1.3 lib/active_support_ext/object/deep_dup.rb
grover-1.1.2 lib/active_support_ext/object/deep_dup.rb
grover-1.1.1 lib/active_support_ext/object/deep_dup.rb
grover-1.1.0 lib/active_support_ext/object/deep_dup.rb
grover-1.0.6 lib/active_support_ext/object/deep_dup.rb
grover-1.0.5 lib/active_support_ext/object/deep_dup.rb
grover-1.0.4 lib/active_support_ext/object/deep_dup.rb
grover-1.0.3 lib/active_support_ext/object/deep_dup.rb
grover-1.0.2 lib/active_support_ext/object/deep_dup.rb
grover-1.0.1 lib/active_support_ext/object/deep_dup.rb