Sha256: da2a5d440caa512dcd49663d8b5743b879e604882293e0e59844d06dfc42de73

Contents?: true

Size: 1.28 KB

Versions: 9

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

# All our Ruby core extensions for the +Hash+ class.
class Hash
  # Perform the regular +Hash#compact+ method on the object but takes care of
  # deeply nested hashs.
  #
  # @return [Hash]
  def deep_compact
    deep_compact_in_object(self)
  end

  # Perform a deep key transformation on the hash,
  # so all keys are in camelcase.
  #
  # @return [Hash]
  def deep_camelize_keys
    deep_transform_keys { |key| key.to_s.camelize(:lower) }
  end

  # Perform a deep key transformation on the hash,
  # so all keys are in snakecase/underscored.
  #
  # @return [Hash]
  def deep_underscore_keys
    deep_transform_keys { |key| key.to_s.underscore }
  end

  private

  # A supporting helper to allow deep hash compaction.
  #
  # @param object [Mixed] the object to compact
  # @return [Mixed] the compacted object
  #
  # rubocop:disable Metrics/MethodLength because of the extra empty
  #   hash compaction logic
  def deep_compact_in_object(object)
    case object
    when Hash
      object = object.compact.transform_values do |value|
        deep_compact_in_object(value)
      end
      object.empty? ? nil : object.compact
    when Array
      object.map { |item| deep_compact_in_object(item) }
    else
      object
    end
  end
  # rubocop:enable Metrics/MethodLength
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
pricehubble-1.3.0 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.5 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.4 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.3 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.2 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.1 lib/price_hubble/core_ext/hash.rb
pricehubble-1.2.0 lib/price_hubble/core_ext/hash.rb
pricehubble-1.1.0 lib/pricehubble/core_ext/hash.rb
pricehubble-1.0.0 lib/pricehubble/core_ext/hash.rb