Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/na/hash.rb

Overview

Extensions to Ruby’s Hash class for symbolizing keys and deep freezing values.

Examples:

Symbolize all keys in a hash

{ 'foo' => 1, 'bar' => { 'baz' => 2 } }.symbolize_keys #=> { :foo => 1, :bar => { :baz => 2 } }

Direct Known Subclasses

NA::Action, NA::Project

Instance Method Summary collapse

Instance Method Details

#deep_freezeObject

Freeze all values in a hash

Examples:

{ foo: { bar: 'baz' } }.deep_freeze

Returns:

  • Hash with all values frozen



24
25
26
27
28
29
30
31
# File 'lib/na/hash.rb', line 24

def deep_freeze
  chilled = {}
  each do |k, v|
    chilled[k] = v.is_a?(Hash) ? v.deep_freeze : v.freeze
  end

  chilled.freeze
end

#deep_freeze!Hash

Freeze all values in a hash in place

Returns:

  • (Hash)

    Hash with all values frozen



36
37
38
# File 'lib/na/hash.rb', line 36

def deep_freeze!
  replace deep_thaw.deep_freeze
end

#deep_merge(second) ⇒ Hash

Recursively merge two hashes, combining arrays and preferring non-nil values

Parameters:

  • second (Hash)

    The hash to merge with

Returns:

  • (Hash)

    The merged hash



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/na/hash.rb', line 63

def deep_merge(second)
  merger = proc { |_, v1, v2|
    if v1.is_a?(Hash) && v2.is_a?(Hash)
      v1.merge(v2, &merger)
    elsif v1.is_a?(Array) && v2.is_a?(Array)
      v1 | v2
    else
      [:undefined, nil, :nil].include?(v2) ? v1 : v2
    end
  }
  merge(second.to_h, &merger)
end

#deep_thawHash

Recursively duplicate all values in a hash

Returns:

  • (Hash)

    Hash with all values duplicated



43
44
45
46
47
48
49
50
# File 'lib/na/hash.rb', line 43

def deep_thaw
  chilled = {}
  each do |k, v|
    chilled[k] = v.is_a?(Hash) ? v.deep_thaw : v.dup
  end

  chilled.dup
end

#deep_thaw!Hash

Recursively duplicate all values in a hash in place

Returns:

  • (Hash)

    Hash with all values duplicated



55
56
57
# File 'lib/na/hash.rb', line 55

def deep_thaw!
  replace deep_thaw
end

#symbolize_keysHash

Convert all keys in the hash to symbols recursively

Examples:

{ 'foo' => 1, 'bar' => { 'baz' => 2 } }.symbolize_keys #=> { :foo => 1, :bar => { :baz => 2 } }

Returns:

  • (Hash)

    Hash with symbolized keys



14
15
16
# File 'lib/na/hash.rb', line 14

def symbolize_keys
  each_with_object({}) { |(k, v), hsh| hsh[k.to_sym] = v.is_a?(Hash) ? v.symbolize_keys : v }
end