Sha256: 79fbacc32abe28f6fce58fb02273fd1516a53d13aaa2449c40fcd787cd712f56
Contents?: true
Size: 1.93 KB
Versions: 13
Compression:
Stored size: 1.93 KB
Contents
module CasinoHub module Util # 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) 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 = [] # 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 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 end end
Version data entries
13 entries across 13 versions & 1 rubygems