class SalsaLabs::ApiClient
Used to request information from Salsa Labs. Handles cookie-based authentication, and raises an exception when the API returns an error.
Attributes
authenticated[R]
email[R]
host[R]
password[R]
Public Class Methods
new(credentials = {})
click to toggle source
# File lib/salsa_labs/api_client.rb, line 10 def initialize(credentials = {}) @email = credentials[:email] || ENV['SALSA_LABS_API_EMAIL'] @password = credentials[:password] || ENV['SALSA_LABS_API_PASSWORD'] @host = credentials[:host] || 'hq-salsa.wiredforchange.com' @authenticated = false end
Public Instance Methods
authenticate()
click to toggle source
# File lib/salsa_labs/api_client.rb, line 18 def authenticate return true if authenticated? response = authenticate! @authentication_cookie = response.env[:response_headers]["set-cookie"] @authenticated = Nokogiri::XML(response.body).css('error').empty? end
authenticated?()
click to toggle source
# File lib/salsa_labs/api_client.rb, line 27 def authenticated? @authenticated end
fetch(endpoint, params)
click to toggle source
# File lib/salsa_labs/api_client.rb, line 31 def fetch(endpoint, params) authenticate unless authenticated? perform_get_request(endpoint, params).body end
Private Instance Methods
authenticate!()
click to toggle source
# File lib/salsa_labs/api_client.rb, line 44 def authenticate! perform_get_request( '/api/authenticate.sjs', authentication_parameters ) end
authentication_parameters()
click to toggle source
# File lib/salsa_labs/api_client.rb, line 51 def authentication_parameters {email: email, password: password} end
connection()
click to toggle source
# File lib/salsa_labs/api_client.rb, line 55 def connection @connection ||= Faraday. new(url: "https://#{host}") do |faraday| faraday.use Faraday::Request::UrlEncoded faraday.adapter Faraday.default_adapter end end
perform_get_request(endpoint, params)
click to toggle source
# File lib/salsa_labs/api_client.rb, line 64 def perform_get_request(endpoint, params) response = connection.get do |request| request.headers['cookie'] = authentication_cookie.to_s request.url(endpoint, params) end raise_if_error!(response) response end
raise_if_error!(response)
click to toggle source
# File lib/salsa_labs/api_client.rb, line 75 def raise_if_error!(response) # Raise SalsaLabs::Error if response.body contains error (need to do this # because API always gives 200 but then gives an error in the XML). errors = Nokogiri::XML(response.body).css('error') if errors.any? raise SalsaLabs::Error.new(response), "There is an error: #{errors.first.text}" end end