lib/stripe/util.rb in stripe-1.29.1 vs lib/stripe/util.rb in stripe-1.30.0

- old
+ new

@@ -1,5 +1,7 @@ +require "cgi" + module Stripe module Util def self.objects_to_ids(h) case h when APIResource @@ -90,26 +92,47 @@ else object end end + # Encodes a hash of parameters in a way that's suitable for use as query + # parameters in a URI or as form parameters in a request body. This mainly + # involves escaping special characters from parameter keys and values (e.g. + # `&`). + def self.encode_parameters(params) + Util.flatten_params(params). + map { |k,v| "#{url_encode(k)}=#{url_encode(v)}" }.join('&') + end + + # Encodes a string in a way that makes it suitable for use in a set of + # query parameters in a URI or in a set of form parameters in a request + # body. def self.url_encode(key) - URI.escape(key.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) + CGI.escape(key.to_s). + # Don't use strict form encoding by changing the square bracket control + # characters back to their literals. This is fine by the server, and + # makes these parameter strings easier to read. + gsub('%5B', '[').gsub('%5D', ']') end def self.flatten_params(params, parent_key=nil) result = [] params.each do |key, value| - calculated_key = parent_key ? "#{parent_key}[#{url_encode(key)}]" : url_encode(key) + calculated_key = parent_key ? "#{parent_key}[#{key}]" : "#{key}" if value.is_a?(Hash) result += flatten_params(value, calculated_key) elsif value.is_a?(Array) result += flatten_params_array(value, calculated_key) else result << [calculated_key, value] end end - result + + # The #sort_by call here is mostly so that we can get some stability in + # our 1.8.7 test suite where Hash key order is not preserved. + # + # https://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/ + result.sort_by { |(k, _)| k } end def self.flatten_params_array(value, calculated_key) result = [] value.each do |elem|