/
api.rb
80 lines (73 loc) · 2.4 KB
/
api.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
module Her
# This class is where all HTTP requests are made. Before using Her, you must configure it
# so it knows where to make those requests. In Rails, this is usually done in `config/initializers/her.rb`:
#
# @example
# $my_api = Her::API.new
# $my_api.setup :base_uri => "https://api.example.com"
class API
# @private
attr_reader :base_uri, :parse_with
# Setup a default API connection
def self.setup(attrs={}) # {{{
@@default_api = new
@@default_api.setup(attrs)
end # }}}
# @private
def self.default_api(attrs={}) # {{{
defined?(@@default_api) ? @@default_api : nil
end # }}}
# Setup the API connection
def setup(attrs={}) # {{{
@base_uri = attrs[:base_uri]
@parse_with = lambda do |response|
json = JSON.parse(response.body, :symbolize_names => true)
{
:data => json[:data],
:errors => json[:errors],
:metadata => json[:metadata],
}
end
@connection = Faraday.new(:url => @base_uri) do |builder|
builder.request :url_encoded
builder.adapter :net_http
end
end # }}}
# Define a custom parsing procedure. The procedure is passed the response object and is
# expected to return a hash with three keys: a main data Hash, an errors Array
# and a metadata Hash.
#
# @example
# $my_api.parse_with do |response|
# json = JSON.parse(response.body)
# { :resource => json[:data], :errors => json[:errors], :metadata => json[:metdata] }
# end
def parse_with(&block) # {{{
@custom_parsing_block = true
@parse_with = block
end # }}}
# Return whether a custom parsing block has been defined
def custom_parsing_block? # {{{
@custom_parsing_block
end # }}}
# Make an HTTP request to the API
def request(attrs={}) # {{{
method = attrs.delete(:_method)
path = attrs.delete(:_path)
@connection.send method do |request|
if method == :get
# For GET requests, treat additional parameters as querystring data
request.url path, attrs
else
# For POST, PUT and DELETE requests, treat additional parameters as request body
request.url path
request.body = attrs
end
end
end # }}}
# Parse the HTTP response
def parse(response) # {{{
@parse_with.call(response)
end # }}}
end
end