Class: SoundCouch::FormRequest

Inherits:
HTTPkit::Request
  • Object
show all
Defined in:
lib/soundcouch/form_request.rb

Constant Summary collapse

BOUNDARY =
'SoundCouchBoundary'

Instance Method Summary collapse

Constructor Details

#initialize(http_method, uri, headers = {}, body = nil) ⇒ FormRequest


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/soundcouch/form_request.rb', line 7

def initialize(http_method, uri, headers = {}, body = nil)
  body &&= begin
    headers['Content-Type'] = 'multipart/form-data; boundary=' + BOUNDARY

    parts = flatten(body).flat_map do |k, v|
      if v.is_a?(Array)
        v.map { |x| Parts::Part.new(BOUNDARY, k, x) }
      else
        Parts::Part.new(BOUNDARY, k, v)
      end
    end + [Parts::EpiloguePart.new(BOUNDARY)]

    CompositeReadIO.new(parts.map(&:to_io)).read
  end

  headers['Accept'] = 'application/json'
  super(http_method, uri, headers, body || '')
end

Instance Method Details

#flatten(body, prefix = '') ⇒ Object


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/soundcouch/form_request.rb', line 26

def flatten(body, prefix = '')
  flattened = []
  body.each do |(k,v)|
    if body.is_a?(Array)
      v = k
      k = ""
    end

    flattened_key = prefix == "" ? "#{k}" : "#{prefix}[#{k}]"
    if v.is_a?(Hash) || v.is_a?(Array)
      flattened += flatten(v, flattened_key)
    else
      flattened << [flattened_key, v]
    end
  end
  flattened
end