Module: Binance::Utils::Faraday::CustomParamsEncoder

Extended by:
Forwardable
Defined in:
lib/binance/utils/faraday/custom_params_encoder.rb

Overview

Custom parameter encoder

Class Method Summary collapse

Class Method Details

.decode(query) ⇒ Object

rubocop:disable Metrics/AbcSize



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/binance/utils/faraday/custom_params_encoder.rb', line 51

def self.decode(query)
  return nil if query.nil?

  param_pairs = split_query query
  param_pairs.each_with_object({}) do |pair, accu|
    key = unescape(pair[0])
    value = pair[1] || true
    value = unescape(value.to_str.gsub(/\+/, ' ')) if value.respond_to?(:to_str)
    if accu[key].is_a?(Array)
      accu[key] << value
    elsif accu[key] # already a value for this key
      accu[key] = [accu[key], value]
    else
      accu[key] = value
    end
  end
end

.encode(params) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/binance/utils/faraday/custom_params_encoder.rb', line 15

def self.encode(params)
  if params.nil?
    nil
  elsif params.is_a?(Array)
    # The params have form [['key1', 'value1'], ['key2', 'value2']].
    encode_array params
  elsif params.respond_to?(:to_hash)
    params = params.to_hash.map do |key, value|
      key = key.to_s if key.is_a?(Symbol)
      [key, value]
    end
    encode_array params
  else
    raise TypeError, "Can't encode #{params.class}."
  end
end

.encode_array(params) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/binance/utils/faraday/custom_params_encoder.rb', line 32

def self.encode_array(params)
  buffer = ''.dup
  params.each do |key, value|
    encoded_key = escape(key)
    if Binance::Utils::Validation.invalid?(value)
      buffer << "#{encoded_key}&"
    elsif value.is_a?(Array)
      value.each do |sub_value|
        buffer << "#{encoded_key}=#{escape sub_value}&"
      end
    else
      value = value.to_s if [true, false].include?(value)
      buffer << "#{encoded_key}=#{value}&"
    end
  end
  buffer.chomp '&'
end

.split_query(query) ⇒ Object

rubocop:enable Metrics/AbcSize



70
71
72
73
74
# File 'lib/binance/utils/faraday/custom_params_encoder.rb', line 70

def self.split_query(query)
  (query.split('&').map do |pair|
    pair.split('=', 2) if pair && !pair.empty?
  end).compact
end