Class: Faraday::Request::Multipart
Constant Summary
collapse
- DEFAULT_BOUNDARY_PREFIX =
"-----------RubyMultipartPost".freeze
Constants inherited
from UrlEncoded
UrlEncoded::CONTENT_TYPE
Instance Method Summary
collapse
Methods inherited from UrlEncoded
#match_content_type, #request_type
Methods inherited from Middleware
dependency, inherited, #initialize, loaded?, new
#fetch_middleware, #load_middleware, #lookup_middleware, #middleware_mutex, #register_middleware
Instance Method Details
#call(env) ⇒ Object
9
10
11
12
13
14
15
16
|
# File 'lib/faraday/request/multipart.rb', line 9
def call(env)
match_content_type(env) do |params|
env.request.boundary ||= unique_boundary
env.[CONTENT_TYPE] += "; boundary=#{env.request.boundary}"
env.body = create_multipart(env, params)
end
@app.call env
end
|
#create_multipart(env, params) ⇒ Object
36
37
38
39
40
41
42
43
44
45
46
|
# File 'lib/faraday/request/multipart.rb', line 36
def create_multipart(env, params)
boundary = env.request.boundary
parts = process_params(params) do |key, value|
Faraday::Parts::Part.new(boundary, key, value)
end
parts << Faraday::Parts::EpiloguePart.new(boundary)
body = Faraday::CompositeReadIO.new(parts)
env.[Faraday::Env::ContentLength] = body.length.to_s
return body
end
|
#has_multipart?(obj) ⇒ Boolean
26
27
28
29
30
31
32
33
34
|
# File 'lib/faraday/request/multipart.rb', line 26
def has_multipart?(obj)
if obj.respond_to?(:each) && !obj.is_a?(String)
(obj.respond_to?(:values) ? obj.values : obj).each do |val|
return true if (val.respond_to?(:content_type) || has_multipart?(val))
end
end
false
end
|
#process_params(params, prefix = nil, pieces = nil, &block) ⇒ Object
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
# File 'lib/faraday/request/multipart.rb', line 52
def process_params(params, prefix = nil, pieces = nil, &block)
params.inject(pieces || []) do |all, (key, value)|
key = "#{prefix}[#{key}]" if prefix
case value
when Array
values = value.inject([]) { |a,v| a << [nil, v] }
process_params(values, key, all, &block)
when Hash
process_params(value, key, all, &block)
else
all << block.call(key, value)
end
end
end
|
#process_request?(env) ⇒ Boolean
18
19
20
21
22
23
24
|
# File 'lib/faraday/request/multipart.rb', line 18
def process_request?(env)
type = request_type(env)
env.body.respond_to?(:each_key) and !env.body.empty? and (
(type.empty? and has_multipart?(env.body)) or
type == self.class.mime_type
)
end
|
#unique_boundary ⇒ Object
48
49
50
|
# File 'lib/faraday/request/multipart.rb', line 48
def unique_boundary
"#{DEFAULT_BOUNDARY_PREFIX}-#{SecureRandom.hex}"
end
|