Class: SummerProject::Base

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

Direct Known Subclasses

Person, Project, User

Class Method Summary collapse

Class Method Details

.default_pathObject



67
68
69
# File 'lib/summer_project/base.rb', line 67

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

.delete(id) ⇒ Object



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

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

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



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

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

.get(params = {}) ⇒ Object



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

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

.handle_response(response, request, result) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/summer_project/base.rb', line 52

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

.path_with_id(id) ⇒ Object



71
72
73
# File 'lib/summer_project/base.rb', line 71

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

.post(params = {}) ⇒ Object



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

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

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



20
21
22
# File 'lib/summer_project/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
# File 'lib/summer_project/base.rb', line 29

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

  path ||= default_path
  url = SummerProject.base_url
  url += '/' unless url.last == '/'
  url += path
  case method
  when :post
    RestClient.post(url, params, authorization: "Bearer #{SummerProject.access_token}", :timeout => -1) { |response, request, result, &block|
      handle_response(response, request, result)
    }
  when :put
    RestClient.put(url, params, authorization: "Bearer #{SummerProject.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 #{SummerProject.access_token}"}, :timeout => -1) { |response, request, result, &block|
      handle_response(response, request, result)
    }
  end
end