class Addressable::URI

def self.form_encode(form_values, sort=false)

Returns:
  • (String) -

Parameters:
  • sort (TrueClass, FalseClass) --
  • form_values (#to_hash, #to_ary) --
def self.form_encode(form_values, sort=false)
  if form_values.respond_to?(:to_hash)
    form_values = form_values.to_hash.to_a
  elsif form_values.respond_to?(:to_ary)
    form_values = form_values.to_ary
  else
    raise TypeError, "Can't convert #{form_values.class} into Array."
  end
  form_values = form_values.inject([]) do |accu, (key, value)|
    if value.kind_of?(Array)
      value.each do |v|
        accu << [key.to_s, v.to_s]
      end
    else
      accu << [key.to_s, value.to_s]
    end
    accu
  end
  if sort
    # Useful for OAuth and optimizing caching systems
    form_values = form_values.sort
  end
  escaped_form_values = form_values.map do |(key, value)|
    # Line breaks are CRLF pairs
    [
      self.encode_component(
        key.gsub(/(\r\n|\n|\r)/, "\r\n"),
        CharacterClasses::UNRESERVED
      ).gsub("%20", "+"),
      self.encode_component(
        value.gsub(/(\r\n|\n|\r)/, "\r\n"),
        CharacterClasses::UNRESERVED
      ).gsub("%20", "+")
    ]
  end
  return escaped_form_values.map do |(key, value)|
    "#{key}=#{value}"
  end.join("&")
end