/
request.rb
121 lines (96 loc) · 2.4 KB
/
request.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
module Nestful
class Request
attr_reader :options, :format, :url
attr_accessor :params, :body, :method, :headers
# Connection options
attr_accessor :proxy, :user, :password, :auth_type, :timeout, :ssl_options
def initialize(url, options = {})
@url = url.to_s
@options = options
@options.each do |key, val|
method = "#{key}="
send(method, val) if respond_to?(method)
end
self.method ||= :get
self.params ||= {}
self.headers ||= {}
self.format ||= :form
end
def format=(mime_or_format)
@format = mime_or_format.is_a?(Symbol) ?
Formats[mime_or_format].new : mime_or_format
end
def url=(value)
@url = value
@uri = nil
@url
end
def uri
return @uri if @uri
url = @url.match(/\Ahttps?:\/\//) ? @url : "http://#{@url}"
@uri = URI.parse(url)
@uri.path = '/' if @uri.path.empty?
@uri.query.split('&').each do |res|
key, value = res.split('=')
@params[key] = value
end if @uri.query
@uri
end
def path
uri.path
end
def execute
if encoded?
result = connection.send(method, path, encoded, build_headers)
else
result = connection.send(method, query_path, build_headers)
end
Response.new(result)
rescue Redirection => error
self.url = error.response['Location']
execute
end
protected
def connection
Connection.new(uri,
:proxy => proxy,
:timeout => timeout,
:ssl_options => ssl_options
)
end
def content_type_headers
if encoded?
{'Content-Type' => format.mime_type}
else
{}
end
end
def auth_headers
if auth_type == :bearer
{ 'Authorization' => "Bearer #{@password}" }
elsif auth_type == :basic
{ 'Authorization' => 'Basic ' + ["#{@user}:#{@password}"].pack('m').delete("\r\n") }
else
{ }
end
end
def build_headers
auth_headers
.merge(content_type_headers)
.merge(headers)
end
def query_path
query_path = path
if params.any?
query_path += '?' + Helpers.to_param(params)
end
query_path
end
def encoded?
[:post, :put].include?(method)
end
def encoded
params.any? ? format.encode(params) : body
end
end
end