Class: Redminerb::Client

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

Overview

HTTP client to communicate w/ the Redmine server.

Defined Under Namespace

Classes: UnprocessableEntity

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cfg) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
# File 'lib/redminerb/client.rb', line 10

def initialize(cfg)
  @connection = Faraday.new(url: cfg.url) do |f|
    f.adapter Faraday.default_adapter
  end
  @connection.basic_auth(cfg.api_key, cfg.api_key)
end

Class Method Details

.raise_error!(res) ⇒ Object

It raises an exception giving the validation messages for 422 responses.



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/redminerb/client.rb', line 42

def self.raise_error!(res)
  if res.status == 422
    begin
      errors = JSON.parse(res.body)['errors']
    rescue JSON::ParserError
      errors = [res.body]
    end
    fail UnprocessableEntity, errors.join("\n")
  else
    fail StandardError, "ERROR (status code #{res.status})"
  end
end

Instance Method Details

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

Makes a GET request of the given ‘path’ param and returns the body of the response parsed as JSON.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/redminerb/client.rb', line 19

def get_json(path, params = {})
  Redminerb.init_required!
  res = _get(path, params)
  if res.status == 404
    fail Redminerb::NotFoundError, path
  else
    JSON.parse(res.body)
  end
rescue JSON::ParserError => e
  raise e, "HTTP status code #{res.status}"
end

#post_json(path, params) ⇒ Object

Makes a POST request to ‘path’ with ‘params’ in JSON format.



32
33
34
35
36
37
38
39
# File 'lib/redminerb/client.rb', line 32

def post_json(path, params)
  Redminerb.init_required!
  @connection.post do |req|
    req.url path
    req.headers['Content-Type'] = 'application/json'
    req.body = params.to_json
  end
end