Class: JsonApiToolbox::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/service.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, url, body) ⇒ Service

Returns a new instance of Service.



11
12
13
14
15
# File 'lib/service.rb', line 11

def initialize(method, url, body)
  @method = method
  @url = url
  @body = body
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



9
10
11
# File 'lib/service.rb', line 9

def body
  @body
end

#methodObject (readonly)

Returns the value of attribute method.



9
10
11
# File 'lib/service.rb', line 9

def method
  @method
end

#urlObject (readonly)

Returns the value of attribute url.



9
10
11
# File 'lib/service.rb', line 9

def url
  @url
end

Class Method Details

.build_query_string(includes, query_string) ⇒ Object



63
64
65
66
67
68
# File 'lib/service.rb', line 63

def build_query_string(includes, query_string)
  params = {}
  params[:includes] = includes if includes
  params.merge!(query_string) if query_string
  params
end

.get(url: nil, includes: nil, query_string: nil) ⇒ Object



45
46
47
48
# File 'lib/service.rb', line 45

def get(url: nil, includes: nil, query_string: nil)
  body = build_query_string(includes, query_string)
  new(:get, url, body).execute
end

.parse_response(response) ⇒ Object



58
59
60
61
# File 'lib/service.rb', line 58

def parse_response(response)
  response_parsed = JSON::Api::Vanilla.parse(response.body)
  response_parsed.data || response_parsed.errors
end

.patch(url: nil, body: nil) ⇒ Object



54
55
56
# File 'lib/service.rb', line 54

def patch(url: nil, body: nil)
  new(:patch, url, body).execute
end

.post(url: nil, body: nil) ⇒ Object



50
51
52
# File 'lib/service.rb', line 50

def post(url: nil, body: nil)
  new(:post, url, body).execute
end

Instance Method Details

#build_bodyObject



40
41
42
# File 'lib/service.rb', line 40

def build_body
  return body if method != :get
end

#build_headerObject



34
35
36
37
38
# File 'lib/service.rb', line 34

def build_header
  headers = { Authorization: RequestStore.store[:token] }
  headers[:params] = body if method == :get
  headers
end

#executeObject



17
18
19
20
21
# File 'lib/service.rb', line 17

def execute
  response = request
  return if response.code == 404
  Service.parse_response(response)
end

#requestObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/service.rb', line 23

def request
  RestClient::Request.execute(
    method: method,
    url: url,
    payload: build_body,
    headers: build_header
  )
rescue RestClient::ExceptionWithResponse => e
  e.response
end