Sha256: 0d3bcdbea866a01e473819ceaa54aa85cd31628b5fcd199522f8376bb4846199

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

# Override Hash class with convience methods
class Hash

  def self.transform_keys_to_symbols(value)
    return value if not value.is_a?(Hash)
    hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
    return hash
  end

  # Take keys of hash and transform those to a symbols
  def transform_keys_to_symbols
    inject({}){|memo, (k, v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
  end

  def find_all_values_for(key)
    result = []
    result << self[key]
    self.values.each do |hash_value|
      values = [hash_value] unless hash_value.is_a? Array
      values.each do |value|
        result += value.find_all_values_for(key) if value.is_a? Hash
      end
    end
    result.compact
  end

  # Value present in nested Hash.
  def include_value?(value)
    each_value do |v|
      return true if v == value
      next unless v.is_a? Hash
      v.each_value do |v|
        return true if v == value
        next unless v.is_a? Hash
        v.each_value do |v|
          return true if v == value
        end
      end
    end
    false
  end

  # Whether key is present at least once
  def include_key?(key)
    result = find_all_values_for key
    result != []
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
soaspec-0.0.9 lib/soaspec/hash_methods.rb
soaspec-0.0.8 lib/soaspec/hash_methods.rb