Module: Remotr::Respondable::ClassMethods

Defined in:
lib/remotr/respondable.rb

Instance Method Summary collapse

Instance Method Details

#applicationObject



19
20
21
# File 'lib/remotr/respondable.rb', line 19

def application
  self.name.deconstantize.underscore
end

#configObject



11
12
13
# File 'lib/remotr/respondable.rb', line 11

def config
  self.name.deconstantize.constantize.config
end

#delete(path = {}, params = {}) ⇒ Object



31
32
33
# File 'lib/remotr/respondable.rb', line 31

def delete(path = {}, params = {})
  request :delete, path, params
end

#get(path = {}, params = {}) ⇒ Object



23
24
25
# File 'lib/remotr/respondable.rb', line 23

def get(path = {}, params = {})
  request :get, path, params
end

#namespaceObject



15
16
17
# File 'lib/remotr/respondable.rb', line 15

def namespace
  self.name.demodulize.pluralize.underscore
end

#post(path = {}, params = {}, body = nil) ⇒ Object



27
28
29
# File 'lib/remotr/respondable.rb', line 27

def post(path = {}, params = {}, body = nil)
  request :post, path, params, body
end

#put(path = {}, params = {}, body = nil) ⇒ Object



35
36
37
# File 'lib/remotr/respondable.rb', line 35

def put(path = {}, params = {}, body = nil)
  request :put, path, params, body
end

#request(method, path, params = {}, body = nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/remotr/respondable.rb', line 39

def request(method, path, params = {}, body = nil)
  path         = "#{config.base_path}#{path}"
  token        = Signature::Token.new application, config.api_key
  request      = Signature::Request.new method.to_s.upcase, path, params
  auth_hash    = request.sign token
  query_params = params.merge auth_hash
  url          = URI.join(config.base_uri, path).to_s

  fail ArgumentError unless %w( get post delete put update ).include? method.to_s
  HTTParty.send method, url, query: query_params, body: body, headers: { 'Accept' => 'application/json' }
end

#respond_with(httparty_response, custom_namespace = nil) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/remotr/respondable.rb', line 51

def respond_with(httparty_response, custom_namespace = nil)
  use_namespace = custom_namespace || namespace
  object = httparty_response.parsed_response ? httparty_response.parsed_response[use_namespace.to_s] : nil

  if httparty_response.code.to_i.between? 200, 299
    Operations.success :remote_request_succeeded, object: object, code: httparty_response.code, body: httparty_response.body
  else
    Operations.failure :remote_request_failed, object: httparty_response, code: httparty_response.code
  end

rescue JSON::ParserError
  Operations.failure :remote_request_parsing_failed, object: httparty_response
end