Sha256: 20d23664994fe2257cca4c03fc2a2a87e0a870e7c379aa548363006e88fcd8db

Contents?: true

Size: 874 Bytes

Versions: 3

Compression:

Stored size: 874 Bytes

Contents

module WithFilters
  # @private
  module HashExtraction
    # Extracts the value from a hash and takes nesting into account.
    #
    # @param [Hash] hash The hash to search.
    # @param [String, Symbol] key The key or nested key to search for.
    #
    # @return [Object, nil]
    #
    # @example Key is a symbol.
    #   extract_hash_key({foo: 'bar'}, :foo) # => 'bar'
    #
    # @example Key is a string with nesting.
    #   extract_hash_key({foo: {bar: 'baz'}}, 'foo[:bar]') # => 'baz'
    #
    # @since 0.1.0
    def extract_hash_value(hash, key)
      key  = key.to_s
      hash = hash.stringify_keys
      
      if hash[key]
        hash[key]
      else
        first_key, remaining_content = key.to_s.match(/^([^\[]+)(.*)$/).captures

        eval "hash[first_key]#{remaining_content.gsub(/\[/, '["').gsub(/]/, '"]')} rescue nil"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
with_filters-0.1.2 lib/with_filters/hash_extraction.rb
with_filters-0.1.1 lib/with_filters/hash_extraction.rb
with_filters-0.1.0 lib/with_filters/hash_extraction.rb