Module: Trifle::Ruby::Mixins::Packer::ClassMethods
- Defined in:
- lib/trifle/ruby/mixins/packer.rb
Instance Method Summary collapse
- #deep_merge(this_hash, other_hash, &block) ⇒ Object
- #deep_merge!(this_hash, other_hash, &block) ⇒ Object
- #pack(hash:, prefix: nil) ⇒ Object
- #unpack(hash:) ⇒ Object
Instance Method Details
#deep_merge(this_hash, other_hash, &block) ⇒ Object
34 35 36 |
# File 'lib/trifle/ruby/mixins/packer.rb', line 34 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
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/trifle/ruby/mixins/packer.rb', line 38 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
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/trifle/ruby/mixins/packer.rb', line 12 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
25 26 27 28 29 30 31 32 |
# File 'lib/trifle/ruby/mixins/packer.rb', line 25 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 |