Module: Latitude::API::RequestParams

Defined in:
lib/latitude/api/request_params.rb

Constant Summary collapse

COMMA_JOIN_LEAVES =
%w[tags extra_fields].freeze

Class Method Summary collapse

Class Method Details

.comma_join?(parent_key, value) ⇒ Boolean

Returns:



44
45
46
47
48
49
50
# File 'lib/latitude/api/request_params.rb', line 44

def comma_join?(parent_key, value)
  return false unless parent_key
  return false unless value.all? { |v| v.is_a?(String) || v.is_a?(Symbol) || v.is_a?(Numeric) }

  leaf = parent_key.split(/[\[\]]/).reject(&:empty?).last
  COMMA_JOIN_LEAVES.include?(leaf)
end

.encode(params) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/latitude/api/request_params.rb', line 10

def encode(params)
  return "" if params.nil? || params.empty?

  parts = []
  flatten(params, nil, parts)
  parts.map { |k, v| "#{URI.encode_www_form_component(k)}=#{URI.encode_www_form_component(v)}" }.join("&")
end

.encode_sort(value) ⇒ Object



63
64
65
66
67
# File 'lib/latitude/api/request_params.rb', line 63

def encode_sort(value)
  return nil if value.nil?

  Array(value).map(&:to_s).reject(&:empty?).join(",")
end

.flatten(value, parent_key, parts) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/latitude/api/request_params.rb', line 18

def flatten(value, parent_key, parts)
  case value
  when Hash
    value.each do |k, v|
      next if v.nil?

      key = parent_key ? "#{parent_key}[#{k}]" : k.to_s
      flatten(v, key, parts)
    end
  when Array
    if comma_join?(parent_key, value)
      parts << [parent_key, value.map(&:to_s).join(",")]
    else
      value.each_with_index do |v, _i|
        flatten(v, "#{parent_key}[]", parts)
      end
    end
  when nil
    nil
  when true, false
    parts << [parent_key, value.to_s]
  else
    parts << [parent_key, scalar(value)]
  end
end

.scalar(value) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/latitude/api/request_params.rb', line 52

def scalar(value)
  case value
  when Time, DateTime
    value.utc.iso8601
  when Date
    value.iso8601
  else
    value.to_s
  end
end