Sha256: 38597835cf376fd5f54164fcbed2dfa97379d96b778e91b2fe7e07eeb8568131

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

require "celsius"

module Celsius::Hash
  #
  # This module provides some helper functions for dealing with hashes
  #
  def self.deep_find_key(object, key)
    results = []

    if key.is_a?(Array)
      key.inject(object) do |memo, key_element|
        deep_find_key(memo, key_element)
      end
    else
      if object.is_a?(Array)
        # flatten(1) prevents unintend array nesting due to recursion
        results.concat object.map { |value| deep_find_key(value, key) }.flatten(1)
      elsif object.is_a?(Hash)
        if object.has_key?(key.to_s) || object.has_key?(key.to_sym)
          results << (object[key.to_s] || object[key.to_sym])
        else
          # its easier to concat an empty array than checking for nil
          results.concat deep_find_key(object.values, key) || []
        end
      end

      # remove nils
      results.compact!

      # in case nothing was found, return nil to ease detecting this case
      results.empty? ? nil : results
    end
  end

  def self.smart_store(hash, key, value)
    if hash[key]
      unless hash[key].is_a?(Array)
        hash[key] = [hash[key]]
      end

      hash[key].push(value)
    else
      hash[key] = value
    end

    hash
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
celsius-0.4.1 lib/celsius/hash.rb