Sha256: 393e64e92dfba57fcbbcbc2a76e07d328dacfb01d5f051eb12c866cce68a0fbf

Contents?: true

Size: 1.63 KB

Versions: 7

Compression:

Stored size: 1.63 KB

Contents

require 'pact_broker/string_refinements'

module PactBroker
  module HashRefinements

    refine Hash do
      using PactBroker::StringRefinements

      def deep_merge(other_hash, &block)
        block_actual = Proc.new {|key, oldval, newval|
            newval = block.call(key, oldval, newval) if block_given?
            [oldval, newval].all? {|v| v.is_a?(Hash)} ? oldval.merge(newval, &block_actual) : newval
        }
        merge(other_hash, &block_actual)
      end

      def symbolize_keys
        symbolize_keys_private(self)
      end

      def snakecase_keys
        snakecase_keys_private(self)
      end

      def slice(*keys)
        keys.each_with_object(Hash.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
      end

      private

      def snakecase_keys_private(params)
        case params
        when Hash
          params.inject({}) do |result, (key, value)|
            snake_key = case key
            when String then key.snakecase
            when Symbol then key.to_s.snakecase.to_sym
            else
              key
            end
            result.merge(snake_key => snakecase_keys_private(value))
          end
        when Array
          params.collect { |value| snakecase_keys_private(value) }
        else
          params
        end

      end

      def symbolize_keys_private(params)
        case params
        when Hash
          params.inject({}) do |result, (key, value)|
            result.merge(key.to_sym => symbolize_keys_private(value))
          end
        when Array
          params.collect { |value| symbolize_keys_private(value) }
        else
          params
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pact_broker-2.57.0 lib/pact_broker/hash_refinements.rb
pact_broker-2.56.1 lib/pact_broker/hash_refinements.rb
pact_broker-2.56.0 lib/pact_broker/hash_refinements.rb
pact_broker-2.55.0 lib/pact_broker/hash_refinements.rb
pact_broker-2.54.0 lib/pact_broker/hash_refinements.rb
pact_broker-2.53.0 lib/pact_broker/hash_refinements.rb
pact_broker-2.52.2 lib/pact_broker/hash_refinements.rb