Class: ShiftPlanning::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/shift_planning/client.rb', line 9

def initialize(config = {})
  raise ArgumentError.new('Missing username') unless config.key?(:username)
  @username = config[:username]

  raise ArgumentError.new('Missing password') unless config.key?(:password)
  @password = config[:password]

  raise ArgumentError.new('Missing api key') unless config.key?(:key)
  @key = config[:key]

  @strict = config.key?(:strict) ? config[:strict] : true
  @url = 'http://www.shiftplanning.com/api/'
  @headers = {
    "Content-Type" => "application/x-www-form-urlencoded"
  }
end

Instance Attribute Details

#strictObject

Returns the value of attribute strict.



7
8
9
# File 'lib/shift_planning/client.rb', line 7

def strict
  @strict
end

Instance Method Details

#authenticateObject



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/shift_planning/client.rb', line 30

def authenticate
  body = body_formatter({
    "key" => @key,
    "request" => {
      "module" => "staff.login",
      "method" => "GET",
      "username" => @username,
      "password" => @password
    }
  })
  response = HTTP.with(@headers).post(@url, body)
  @token = JSON.parse(response)["token"]
end

#authenticated?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/shift_planning/client.rb', line 26

def authenticated?
  !@token.nil?
end

#body_formatter(body) ⇒ Object



63
64
65
66
67
# File 'lib/shift_planning/client.rb', line 63

def body_formatter(body)
  {
    :body => "data=#{JSON.dump(body)}"
  }
end

#is_error_response?(response) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/shift_planning/client.rb', line 59

def is_error_response?(response)
  response["status"] != 1
end

#request(method, api_module, request) ⇒ Object

Raises:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/shift_planning/client.rb', line 44

def request(method, api_module, request)
  authenticate unless authenticated?

  body = body_formatter({
    "token" => @token,
    "method" => method,
    "module" => api_module,
    "request" => request
  })
  response = HTTP.with(@headers).post(@url, body)
  result = JSON.parse(response)
  raise ApiError.new(result) if @strict && is_error_response?(result)
  result
end