Sha256: ec371bfd6b341e7d1467b5aacb50278a1f11257a3dfb3571313e37d097d1fabd

Contents?: true

Size: 1.79 KB

Versions: 7

Compression:

Stored size: 1.79 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

  # Loop through each item within a key within a Hash if the key exists
  # @param [Key] Key within hash to iterate through
  def each_if_not_null(key)
    case key.class.to_s
      when 'String'
        if self[key]
          self[key].each do |list_item|
            yield(list_item)
          end
        end
      when 'Array'
        if self[key[0]]
          if self[key[0]][key[1]]
            self[key[0]][key[1]].each do |list_item|
              yield(list_item)
            end
          end
        end
    end
  end

end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
soaspec-0.0.16 lib/soaspec/hash_methods.rb
soaspec-0.0.15 lib/soaspec/hash_methods.rb
soaspec-0.0.14 lib/soaspec/hash_methods.rb
soaspec-0.0.13 lib/soaspec/hash_methods.rb
soaspec-0.0.12 lib/soaspec/hash_methods.rb
soaspec-0.0.11 lib/soaspec/hash_methods.rb
soaspec-0.0.10 lib/soaspec/hash_methods.rb