module Mycrm::Connectable

this module adds connectivity methods to the descendant's class

Constants

DEFAULT_TOKEN_EXPIRE_IN_STORAGE
TOKEN_KEY

Public Class Methods

connection() { |faraday| ... } click to toggle source

create the connection with basic configurations

# File lib/mycrm/connectable.rb, line 16
def connection
  Faraday.new(url: Mycrm.configuration.base_uri) do |faraday|
    faraday.request :url_encoded
    if Mycrm.configuration.logger
      faraday.response :logger, Mycrm.configuration.logger, bodies: true
    end
    yield(faraday) if block_given?
    faraday.adapter Faraday.default_adapter
  end
rescue Errno::ECONNREFUSED => e
  raise ConnectionError, e
end
credentials() click to toggle source
# File lib/mycrm/connectable.rb, line 55
def credentials
  %w(username password).each_with_object({}) do |f, o|
    o[f] = Mycrm.configuration.send(f)
  end
end
extended(descendant) click to toggle source
# File lib/mycrm/connectable.rb, line 10
def self.extended(descendant)
  descendant.send(:extend, ExtendedMethods)
end
fetch_token() click to toggle source
# File lib/mycrm/connectable.rb, line 33
def fetch_token
  storage = Mycrm.configuration.storage # Redis or any strategy that implement set and get

  if storage
    token = storage.get(TOKEN_KEY)
    if token && !(token.nil? || token.empty?)
      token
    else
      token_storage_expiry = Mycrm.configuration.token_storage_expiry || DEFAULT_TOKEN_EXPIRE_IN_STORAGE
      token = fetch_token_from_mycrm
      storage.set(TOKEN_KEY, token, ex: token_storage_expiry)
      token
    end
  else
    fetch_token_from_mycrm
  end
end
fetch_token_from_mycrm() click to toggle source
# File lib/mycrm/connectable.rb, line 51
def fetch_token_from_mycrm
  connection.post('/Login', credentials).body
end
session() { || ... } click to toggle source
# File lib/mycrm/connectable.rb, line 61
def session
  @token = token
  yield if block_given?
ensure
  @token = nil
end
token() click to toggle source
# File lib/mycrm/connectable.rb, line 29
def token
  @token || fetch_token
end