Sha256: 79e423a2483b5193b629d83bbd50eca8895367ab335391a69b738b4c68e47bf6

Contents?: true

Size: 1.38 KB

Versions: 14

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

module Trifle
  module Stats
    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
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
trifle-stats-1.3.1 lib/trifle/stats/mixins/packer.rb
trifle-stats-1.3.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-1.2.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-1.1.2 lib/trifle/stats/mixins/packer.rb
trifle-stats-1.1.1 lib/trifle/stats/mixins/packer.rb
trifle-stats-1.0.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.4.1 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.4.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.3.2 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.3.1 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.3.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.2.1 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.2.0 lib/trifle/stats/mixins/packer.rb
trifle-stats-0.1.0 lib/trifle/stats/mixins/packer.rb