Sha256: 62127fc1a361d62b487b36e9bd0a2c6a41e1239dd9158ff5afb504fa6c06a1f8

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 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_fetch(hash, key)
    result = hash[key.to_s]
    result = result.nil? ? hash[key.to_sym] : result
  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.3 lib/celsius/hash.rb