Module: MerchantZip::Util
- Defined in:
- lib/merchant-zip/util.rb
Class Method Summary collapse
-
.encode_parameters(params) ⇒ Object
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.
- .flatten_params(params, parent_key = nil) ⇒ Object
- .flatten_params_array(value, calculated_key) ⇒ Object
-
.url_encode(key) ⇒ Object
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.
Class Method Details
.encode_parameters(params) ⇒ Object
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. ‘&`).
7 8 9 10 |
# File 'lib/merchant-zip/util.rb', line 7 def self.encode_parameters(params) Util.flatten_params(params). map { |k,v| "#{url_encode(k)}=#{url_encode(v)}" }.join('&') end |
.flatten_params(params, parent_key = nil) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/merchant-zip/util.rb', line 23 def self.flatten_params(params, parent_key=nil) result = [] # do not sort the final output because arrays (and arrays of hashes # especially) can be order sensitive, but do sort incoming parameters params.each do |key, value| calculated_key = parent_key ? "#{parent_key}[#{key}]" : "#{key}" if value.is_a?(Hash) result += flatten_params(value, calculated_key) elsif value.is_a?(Array) check_array_of_maps_start_keys!(value) result += flatten_params_array(value, calculated_key) else result << [calculated_key, value] end end result end |
.flatten_params_array(value, calculated_key) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/merchant-zip/util.rb', line 43 def self.flatten_params_array(value, calculated_key) result = [] value.each do |elem| if elem.is_a?(Hash) result += flatten_params(elem, "#{calculated_key}[]") elsif elem.is_a?(Array) result += flatten_params_array(elem, calculated_key) else result << ["#{calculated_key}[]", elem] end end result end |
.url_encode(key) ⇒ Object
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.
15 16 17 18 19 20 21 |
# File 'lib/merchant-zip/util.rb', line 15 def self.url_encode(key) 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 |