module Faraday::DecodeMethods
def add_to_context(is_array, context, value, subkey)
def add_to_context(is_array, context, value, subkey) is_array ? context << value : context[subkey] = value end
def decode(query)
-
(TypeError)
- if the nesting is incorrect
Returns:
-
(Array
- the decoded params)
Parameters:
-
query
(nil, String
) --
def decode(query) return nil if query.nil? params = {} query.split('&').each do |pair| next if pair.empty? key, value = pair.split('=', 2) key = unescape(key) value = unescape(value.tr('+', ' ')) if value decode_pair(key, value, params) end dehash(params, 0) end
def decode_pair(key, value, context)
def decode_pair(key, value, context) subkeys = key.scan(SUBKEYS_REGEX) subkeys.each_with_index do |subkey, i| is_array = subkey =~ /[\[\]]+\Z/ subkey = Regexp.last_match.pre_match if is_array last_subkey = i == subkeys.length - 1 context = prepare_context(context, subkey, is_array, last_subkey) add_to_context(is_array, context, value, subkey) if last_subkey end end
def dehash(hash, depth)
FIXME: this is not compatible with Rack::Utils.parse_nested_query
Internal: convert a nested hash with purely numeric keys into an array.
def dehash(hash, depth) hash.each do |key, value| hash[key] = dehash(value, depth + 1) if value.is_a?(Hash) end if depth.positive? && !hash.empty? && hash.keys.all? { |k| k =~ /^\d+$/ } hash.sort.map(&:last) else hash end end
def match_context(context, subkey)
def match_context(context, subkey) context << {} if !context.last.is_a?(Hash) || context.last.key?(subkey) context.last end
def new_context(subkey, is_array, context)
def new_context(subkey, is_array, context) value_type = is_array ? Array : Hash if context[subkey] && !context[subkey].is_a?(value_type) raise TypeError, "expected #{value_type.name} " \ "(got #{context[subkey].class.name}) for param `#{subkey}'" end context[subkey] ||= value_type.new end
def prepare_context(context, subkey, is_array, last_subkey)
def prepare_context(context, subkey, is_array, last_subkey) if !last_subkey || is_array context = new_context(subkey, is_array, context) end if context.is_a?(Array) && !is_array context = match_context(context, subkey) end context end