Module: Faraday::EncodeMethods

Included in:
NestedParamsEncoder
Defined in:
lib/faraday/encoders/nested_params_encoder.rb

Overview

Sub-module for encoding parameters into query-string.

Instance Method Summary collapse

Instance Method Details

#encode(params) ⇒ String

Returns the encoded params.

Parameters:

  • params (nil, Array, #to_hash)

    parameters to be encoded

Returns:

  • (String)

    the encoded params

Raises:

  • (TypeError)

    if params can not be converted to a Hash


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/faraday/encoders/nested_params_encoder.rb', line 11

def 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

    # Only to be used for non-Array inputs. Arrays should preserve order.
    params.sort! if @sort_params
  end

  # The params have form [['key1', 'value1'], ['key2', 'value2']].
  buffer = +''
  params.each do |parent, value|
    encoded_parent = escape(parent)
    buffer << "#{encode_pair(encoded_parent, value)}&"
  end
  buffer.chop
end