Module: RightSupport::Data::HashTools

Defined in:
lib/right_support/data/hash_tools.rb

Overview

various tools for manipulating hash-like classes.

Defined Under Namespace

Classes: DeepSortedJsonState, NoJson

Constant Summary collapse

HAS_JSON =
require_succeeds?('json')

Class Method Summary collapse

Class Method Details

.deep_apply_diff!(target, diff) ⇒ Object

Recursively apply diff portion of a patch (generated by deep_create_patch, etc.).

Parameters

Return

Parameters:

  • target (Hash)

    hash where diff will be applied.

  • diff (Hash)

    hash containing changes to apply.

  • target (Hash)

    hash with diff applied.



251
252
253
254
255
256
257
258
259
260
# File 'lib/right_support/data/hash_tools.rb', line 251

def self.deep_apply_diff!(target, diff)
  diff.each do |k, v|
    if v[:left] && v[:right]
      target[k] = v[:right] if v[:left] == target[k]
    elsif target.has_key?(k)
      deep_apply_diff!(target[k], v)
    end
  end
  target
end

.deep_apply_patch!(target, patch) ⇒ Object

Perform 3-way merge using given target and a patch hash (generated by deep_create_patch, etc.). values in target whose keys are in :left_only component of patch are removed values in :right_only component of patch get deep merged into target values in target whose keys are in :diff component of patch and which are identical to left side of diff get overwritten with right side of patch

Parameters

Return

Parameters:

  • target (Hash)

    hash where patch will be applied.

  • patch (Hash)

    hash containing changes to apply.

  • target (Hash)

    hash with patch applied.



236
237
238
239
240
241
# File 'lib/right_support/data/hash_tools.rb', line 236

def self.deep_apply_patch!(target, patch)
  deep_remove!(target, patch[:left_only])
  deep_merge!(target, patch[:right_only])
  deep_apply_diff!(target, patch[:diff])
  target
end

.deep_clone(original) {|value| ... } ⇒ Hash

Creates a deep clone of the given hash.

note that not all objects are clonable in Ruby even though all respond to clone (which is completely counter-intuitive and contrary to all other managed languages). Java, for example, has the built-in Cloneable marker interface which we will simulate here with .duplicable? (because cloneable isn’t actually a word) in case you need non-hash values to be deep-cloned by this method.

also note that .duplicable? may imply caling .dup instead of .clone but developers tend to override .clone and totally forget to override .dup (and having two names for the same method is, yes, a bad idea in any language).

Parameters

Block

Return

Parameters:

  • original (Hash)

    hash to clone

Yield Parameters:

Yield Returns:

  • (Object)

    cloned value of leaf or original value

Returns:

  • (Hash)

    deep cloned hash



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/right_support/data/hash_tools.rb', line 134

def self.deep_clone(original, &leaf_callback)
  result = original.clone
  result.each do |k, v|
    if hashable?(v)
      result[k] = deep_clone(v)
    elsif leaf_callback
      result[k] = leaf_callback.call(v)
    elsif v.respond_to?(:duplicable?)
      result[k] = (v.duplicable? ? v.clone : v)
    else
      result[k] = v
    end
  end
  result
end

.deep_create_patch(left, right) ⇒ Hash

Produce a difference from two hashes. The difference excludes any values which are common to both hashes.

The result is a hash with the following keys:

- :diff = hash with key common to both input hashes and value composed of the corresponding different values: { :left => <left value>, :right => <right value> }
- :left_only = hash composed of items only found in left hash
- :right_only = hash composed of items only found in right hash

Parameters

Return

Parameters:

  • left (Hash)

    side

  • right (Hash)

    side

Returns:

  • (Hash)

    result as hash of diffage



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/right_support/data/hash_tools.rb', line 204

def self.deep_create_patch(left, right)
  result = { :diff=>{}, :left_only=>{}, :right_only=>{} }
  right.each do |k, v|
    if left.include?(k)
      if hashable?(v) && hashable?(left[k])
        subdiff = deep_create_patch(left[k], v)
        result[:right_only].merge!(k=>subdiff[:right_only]) unless subdiff[:right_only].empty?
        result[:left_only].merge!(k=>subdiff[:left_only]) unless subdiff[:left_only].empty?
        result[:diff].merge!(k=>subdiff[:diff]) unless subdiff[:diff].empty?
      elsif v != left[k]
        result[:diff].merge!(k=>{:left => left[k], :right=>v})
      end
    else
      result[:right_only].merge!({ k => v })
    end
  end
  left.each { |k, v| result[:left_only].merge!({ k => v }) unless right.include?(k) }
  result
end

.deep_get(hash, path) ⇒ Object

Gets a value from a (deep) hash using a path given as an array of keys.

Parameters

Return

Parameters:

  • hash (Hash)

    for lookup or nil or empty

  • path (Array)

    to existing value as array of keys or nil or empty

Returns:



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/right_support/data/hash_tools.rb', line 65

def self.deep_get(hash, path)
  hash ||= {}
  path ||= []
  last_index = path.size - 1
  path.each_with_index do |key, index|
    value = hash[key]
    if index == last_index
      return value
    elsif hashable?(value)
      hash = value
    else
      break
    end
  end
  nil
end

.deep_merge!(target, source) ⇒ Hash

Performs a deep merge (but not a deep clone) of one hash into another.

Parameters

Return

Parameters:

  • target (Hash)

    hash to contain original and merged data

  • source (Hash)

    hash containing data to recursively assign or nil or empty

Returns:

  • (Hash)

    to_hash result of merge



158
159
160
161
162
163
164
165
166
167
# File 'lib/right_support/data/hash_tools.rb', line 158

def self.deep_merge!(target, source)
  source.each do |k, v|
    if hashable?(target[k]) && hashable?(v)
      deep_merge!(target[k], v)
    else
      target[k] = v
    end
  end if source
  target
end

.deep_remove!(target, source) ⇒ Hash

Remove recursively values that exist equivalently in the match hash.

Parameters

Return

Parameters:

  • target (Hash)

    hash from which to remove matching values

  • source (Hash)

    hash to compare against target for removal or nil or empty

Returns:

  • (Hash)

    target hash with matching values removed, if any



177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/right_support/data/hash_tools.rb', line 177

def self.deep_remove!(target, source)
  source.each do |k, v|
    if target.has_key?(k)
      if target[k] == v
        target.delete(k)
      elsif hashable?(v) && hashable?(target[k])
        deep_remove!(target[k], v)
      end
    end
  end if source
  target
end

.deep_set!(hash, path, value, clazz = nil) ⇒ TrueClass

Set a given value on a (deep) hash using a path given as an array of keys.

Parameters

Return

Parameters:

  • hash (Hash)

    for insertion

  • path (Array)

    to new value as array of keys

  • value (Object)

    to insert

  • clazz (Class) (defaults to: nil)

    to allocate as needed when building deep hash or nil to infer from hash argument

Returns:

  • (TrueClass)

    always true

Raises:

  • (ArgumentError)


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/right_support/data/hash_tools.rb', line 92

def self.deep_set!(hash, path, value, clazz=nil)
  raise ArgumentError.new("hash is invalid") unless hashable?(hash)
  raise ArgumentError.new("path is invalid") if path.empty?
  clazz ||= hash.class
  raise ArgumentError.new("clazz is invalid") unless hash_like?(clazz)
  last_index = path.size - 1
  path.each_with_index do |key, index|
    if index == last_index
      hash[key] = value
    else
      subhash = hash[key]
      unless hashable?(subhash)
        subhash = clazz.new
        hash[key] = subhash
      end
      hash = subhash
    end
  end
  true
end

.deep_sorted_json(hash, pretty = false) ⇒ String

Generates JSON from the given hash (of hashes) that is sorted by key at all levels. Does not handle case of hash to array of hashes, etc.

Parameters

Return

Parameters:

  • hash (Hash)

    from which to generate JSON

  • pretty (TrueClass|FalseClass) (defaults to: false)

    is true to invoke JSON::pretty_generate, false to call JSON::dump

Returns:

  • (String)

    result as a deep-sorted JSONized hash



341
342
343
344
345
346
347
348
349
# File 'lib/right_support/data/hash_tools.rb', line 341

def self.deep_sorted_json(hash, pretty=false)
  if HAS_JSON
    raise ArgumentError("'hash' was not hashable") unless hashable?(hash)
    state = ::RightSupport::Data::HashTools::DeepSortedJsonState.new(pretty)
    state.generate(hash)
  else
    raise NoJson, "JSON is unavailable"
  end
end

.hash_like?(clazz) ⇒ TrueClass|FalseClass

Determines if given class is hash-like (i.e. instance of class responds to hash methods).

Parameters

Return

Parameters:

  • clazz (Class)

    to be tested

Returns:

  • (TrueClass|FalseClass)

    true if clazz is hash-like, false otherwise



53
54
55
# File 'lib/right_support/data/hash_tools.rb', line 53

def self.hash_like?(clazz)
  clazz.public_method_defined?('has_key?')
end

.hashable?(object) ⇒ TrueClass|FalseClass

Determines if given object is hashable (i.e. object responds to hash methods).

Parameters

Return

Parameters:

  • object (Object)

    to be tested

Returns:

  • (TrueClass|FalseClass)

    true if object is hashable, false otherwise



37
38
39
40
41
42
43
44
# File 'lib/right_support/data/hash_tools.rb', line 37

def self.hashable?(object)
  # note that we could obviously be more critical here, but this test has always been
  # sufficient and excludes Arrays and Strings which respond to [] but not has_key?
  #
  # what we specifically don't want to do is .kind_of?(Hash) because that excludes the
  # range of hash-like classes (such as Chef::Node::Attribute)
  object.respond_to?(:has_key?)
end