Method: Addressable::URI.form_encode
- Defined in:
- lib/addressable/uri.rb
.form_encode(form_values, sort = false) ⇒ String
Encodes a set of key/value pairs according to the rules for the
application/x-www-form-urlencoded MIME type.
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 |
# File 'lib/addressable/uri.rb', line 844 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"), CharacterClassesRegexps::UNRESERVED ).gsub("%20", "+"), self.encode_component( value.gsub(/(\r\n|\n|\r)/, "\r\n"), CharacterClassesRegexps::UNRESERVED ).gsub("%20", "+") ] end return escaped_form_values.map do |(key, value)| "#{key}=#{value}" end.join("&") end |