Module: BellyWash::Mixins::Packer::ClassMethods

Defined in:
lib/belly_wash/mixins/packer.rb

Instance Method Summary collapse

Instance Method Details

#deep_merge(this_hash, other_hash, &block) ⇒ Object



33
34
35
# File 'lib/belly_wash/mixins/packer.rb', line 33

def deep_merge(this_hash, other_hash, &block)
  deep_merge!(this_hash.dup, other_hash, &block)
end

#deep_merge!(this_hash, other_hash, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/belly_wash/mixins/packer.rb', line 37

def deep_merge!(this_hash, other_hash, &block)
  this_hash.merge!(other_hash) do |key, this_val, other_val|
    if this_val.is_a?(Hash) && other_val.is_a?(Hash)
      deep_merge(this_val, other_val, &block)
    elsif block_given?
      block.call(key, this_val, other_val)
    else
      other_val
    end
  end
end

#pack(hash:, prefix: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/belly_wash/mixins/packer.rb', line 11

def pack(hash:, prefix: nil)
  hash.inject({}) do |o, (k, v)|
    key = [prefix, k].compact.join('.')
    if v.instance_of?(Hash)
      o.update(
        pack(hash: v, prefix: key)
      )
    else
      o.update({ key => v })
    end
  end
end

#unpack(hash:) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/belly_wash/mixins/packer.rb', line 24

def unpack(hash:)
  hash.inject({}) do |out, (key, v)|
    deep_merge(
      out,
      key.split('.').reverse.inject(v.to_i) { |o, k| { k => o } }
    )
  end
end