Sha256: ffa7076a0de82f5a38954e0dc193ee8ce02834f3bf0be67b2f312fa6914f2f23

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

module BellyWash
  module Mixins
    module Packer
      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods
        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

        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

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

        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
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
belly_wash-0.1.1 lib/belly_wash/mixins/packer.rb