/
multipart.rb
83 lines (68 loc) · 2.19 KB
/
multipart.rb
1
2
3
4
5
6
7
8
9
10
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module OauthMultipart
end
require "oauth"
OAuth::Consumer.class_eval do
def create_http_request_with_multipart(http_method, path, *arguments)
http_method = http_method.to_sym
if [:post, :put].include?(http_method)
data = arguments.shift
end
# if the base site contains a path, add it now
uri = URI.parse(site)
path = uri.path + path if uri.path
headers = arguments.first.is_a?(Hash) ? arguments.shift : {}
case http_method
when :post
request = Net::HTTP::Post.new(path,headers)
request["Content-Length"] = '0' # Default to 0
when :put
request = Net::HTTP::Put.new(path,headers)
request["Content-Length"] = '0' # Default to 0
when :get
request = Net::HTTP::Get.new(path,headers)
when :delete
request = Net::HTTP::Delete.new(path,headers)
when :head
request = Net::HTTP::Head.new(path,headers)
when :multipart_post
request = Net::HTTP::Post::Multipart.new(path, headers)
else
raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}"
end
if data.is_a?(Hash)
form_data = {}
data.each {|k,v| form_data[k.to_s] = v if !v.nil?}
request.set_form_data(form_data)
elsif data
if data.respond_to?(:read)
request.body_stream = data
if data.respond_to?(:length)
request["Content-Length"] = data.length.to_s
elsif data.respond_to?(:stat) && data.stat.respond_to?(:size)
request["Content-Length"] = data.stat.size.to_s
else
raise ArgumentError, "Don't know how to send a body_stream that doesn't respond to .length or .stat.size"
end
else
request.body = data.to_s
request["Content-Length"] = request.body.length.to_s
end
end
request
end
alias_method_chain :create_http_request,:multipart
end
OAuth::AccessToken.class_eval do
def post_with_multipart(*args)
uri,headers,options = args
if headers && headers.find{|key,value| value.is_a?(UploadIO) }
multipart_post *args
else
post_without_multipart(*args)
end
end
alias_method_chain :post,:multipart
def multipart_post(*args)
request(:multipart_post,*args)
end
end