Module: Faraday::FlatParamsEncoder
- Extended by:
- Forwardable
- Defined in:
- lib/faraday/encoders/flat_params_encoder.rb
Overview
FlatParamsEncoder manages URI params as a flat hash. Any Array values repeat the parameter multiple times.
Class Method Summary collapse
-
.decode(query) ⇒ Hash
Decode converts the given URI querystring into a hash.
-
.encode(params) ⇒ String
Encode converts the given param into a URI querystring.
Class Method Details
.decode(query) ⇒ Hash
Decode converts the given URI querystring into a hash.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/faraday/encoders/flat_params_encoder.rb', line 70 def self.decode(query) return nil if query.nil? empty_accumulator = {} split_query = (query.split('&').map do |pair| pair.split('=', 2) if pair && !pair.empty? end).compact split_query.each_with_object(empty_accumulator.dup) do |pair, accu| pair[0] = unescape(pair[0]) pair[1] = true if pair[1].nil? if pair[1].respond_to?(:to_str) pair[1] = unescape(pair[1].to_str.tr('+', ' ')) end if accu[pair[0]].is_a?(Array) accu[pair[0]] << pair[1] elsif accu[pair[0]] accu[pair[0]] = [accu[pair[0]], pair[1]] else accu[pair[0]] = pair[1] end end end |
.encode(params) ⇒ String
Encode converts the given param into a URI querystring. Keys and values will converted to strings and appropriately escaped for the URI.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/faraday/encoders/flat_params_encoder.rb', line 23 def self.encode(params) return nil if params.nil? unless params.is_a?(Array) unless params.respond_to?(:to_hash) raise TypeError, "Can't convert #{params.class} into Hash." end params = params.to_hash params = params.map do |key, value| key = key.to_s if key.is_a?(Symbol) [key, value] end # Useful default for OAuth and caching. # Only to be used for non-Array inputs. Arrays should preserve order. params.sort! end # The params have form [['key1', 'value1'], ['key2', 'value2']]. buffer = +'' params.each do |key, value| encoded_key = escape(key) if value.nil? buffer << "#{encoded_key}&" elsif value.is_a?(Array) value.each do |sub_value| encoded_value = escape(sub_value) buffer << "#{encoded_key}=#{encoded_value}&" end else encoded_value = escape(value) buffer << "#{encoded_key}=#{encoded_value}&" end end buffer.chop end |