Class: GlobalRegistry::Base

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

Class Method Summary collapse

Class Method Details

.default_pathObject



70
71
72
# File 'lib/global_registry/base.rb', line 70

def self.default_path
  to_s.split('::').last.underscore.pluralize
end

.delete(id) ⇒ Object



24
25
26
# File 'lib/global_registry/base.rb', line 24

def self.delete(id)
  request(:delete, {}, path_with_id(id))
end

.find(id) ⇒ Object



8
9
10
# File 'lib/global_registry/base.rb', line 8

def self.find(id)
  request(:get, {}, path_with_id(id))
end

.get(params = {}) ⇒ Object



12
13
14
# File 'lib/global_registry/base.rb', line 12

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

.handle_response(response, request, result) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/global_registry/base.rb', line 53

def self.handle_response(response, request, result)
  case response.code
  when 200..299
    Oj.load(response)
  when 400
    raise RestClient::BadRequest, response
  when 404
    raise RestClient::ResourceNotFound, response
  when 500
    raise RestClient::InternalServerError, response
  else
    puts response.inspect
    puts request.inspect
    raise result.to_s
  end
end

.path_with_id(id) ⇒ Object



74
75
76
# File 'lib/global_registry/base.rb', line 74

def self.path_with_id(id)
  "#{default_path}/#{id}"
end

.post(params = {}) ⇒ Object



16
17
18
# File 'lib/global_registry/base.rb', line 16

def self.post(params = {})
  request(:post, params)
end

.put(id, params = {}) ⇒ Object



20
21
22
# File 'lib/global_registry/base.rb', line 20

def self.put(id, params = {})
  request(:put, params, path_with_id(id))
end

.request(method, params, path = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/global_registry/base.rb', line 29

def self.request(method, params, path = nil)
  raise 'You need to configure GlobalRegistry with your access_token.' unless GlobalRegistry.access_token

  path ||= default_path
  url = GlobalRegistry.base_url
  url += '/' unless url.last == '/'
  url += path

  case method
  when :post
    RestClient.post(url, params.to_json, :content_type => :json, :accept => :json, authorization: "Bearer #{GlobalRegistry.access_token}", :timeout => -1) { |response, request, result, &block|
      handle_response(response, request, result)
    }
  when :put
    RestClient.put(url, params.to_json, :content_type => :json, :accept => :json, authorization: "Bearer #{GlobalRegistry.access_token}", :timeout => -1) { |response, request, result, &block|
      handle_response(response, request, result)
    }
  else
    RestClient::Request.execute(:method => method, :url => url, :headers => {params: params, authorization: "Bearer #{GlobalRegistry.access_token}", :accept => :json}, :timeout => -1) { |response, request, result, &block|
      handle_response(response, request, result)
    }
  end
end