class ShiftPlanning::Client

Attributes

strict[RW]

Public Class Methods

new(config = {}) click to toggle source
# 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

Public Instance Methods

authenticate() click to toggle source
# 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?() click to toggle source
# File lib/shift_planning/client.rb, line 26
def authenticated?
  !@token.nil?
end
body_formatter(body) click to toggle source
# File lib/shift_planning/client.rb, line 63
def body_formatter(body)
  {
    :body => "data=#{JSON.dump(body)}"
  }
end
is_error_response?(response) click to toggle source
# File lib/shift_planning/client.rb, line 59
def is_error_response?(response)
  response["status"] != 1
end
request(method, api_module, request) click to toggle source
# 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