module Faraday::EncodeMethods

def encode(params)

Raises:
  • (TypeError) - if params can not be converted to a Hash

Returns:
  • (String) - the encoded params

Parameters:
  • params (nil, Array, #to_hash) -- parameters to be encoded
def encode(params)
  return nil if params.nil?
  unless params.is_a?(Array)
    unless params.respond_to?(:to_hash)
      raise TypeError, "Can't convert #{params.class} into Hash."
    end
    params = params.to_hash
    params = params.map do |key, value|
      key = key.to_s if key.is_a?(Symbol)
      [key, value]
    end
    # Only to be used for non-Array inputs. Arrays should preserve order.
    params.sort! if @sort_params
  end
  # The params have form [['key1', 'value1'], ['key2', 'value2']].
  buffer = +''
  params.each do |parent, value|
    encoded_parent = escape(parent)
    buffer << "#{encode_pair(encoded_parent, value)}&"
  end
  buffer.chop
end

def encode_array(parent, value)

def encode_array(parent, value)
  return "#{parent}%5B%5D" if value.empty?
  buffer = +''
  value.each_with_index do |val, index|
    new_parent = if @array_indices
                   "#{parent}%5B#{index}%5D"
                 else
                   "#{parent}%5B%5D"
                 end
    buffer << "#{encode_pair(new_parent, val)}&"
  end
  buffer.chop
end

def encode_hash(parent, value)

def encode_hash(parent, value)
  value = value.map { |key, val| [escape(key), val] }.sort
  buffer = +''
  value.each do |key, val|
    new_parent = "#{parent}%5B#{key}%5D"
    buffer << "#{encode_pair(new_parent, val)}&"
  end
  buffer.chop
end

def encode_pair(parent, value)

def encode_pair(parent, value)
  if value.is_a?(Hash)
    encode_hash(parent, value)
  elsif value.is_a?(Array)
    encode_array(parent, value)
  elsif value.nil?
    parent
  else
    encoded_value = escape(value)
    "#{parent}=#{encoded_value}"
  end
end