Module: Mycrm::Connectable

Defined in:
lib/mycrm/connectable.rb

Overview

this module adds connectivity methods to the descendant’s class

Defined Under Namespace

Modules: ExtendedMethods

Constant Summary collapse

TOKEN_KEY =
'mycrm_auth_token_key'
DEFAULT_TOKEN_EXPIRE_IN_STORAGE =

10 minutes

600

Class Method Summary collapse

Class Method Details

.connectionObject

create the connection with basic configurations



16
17
18
19
20
21
22
23
24
25
26
27
# 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

.credentialsObject



55
56
57
58
59
# 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) ⇒ Object



10
11
12
# File 'lib/mycrm/connectable.rb', line 10

def self.extended(descendant)
  descendant.send(:extend, ExtendedMethods)
end

.fetch_tokenObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 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_mycrmObject



51
52
53
# File 'lib/mycrm/connectable.rb', line 51

def fetch_token_from_mycrm
  connection.post('/Login', credentials).body
end

.sessionObject



61
62
63
64
65
66
# File 'lib/mycrm/connectable.rb', line 61

def session
  @token = token
  yield if block_given?
ensure
  @token = nil
end

.tokenObject



29
30
31
# File 'lib/mycrm/connectable.rb', line 29

def token
  @token || fetch_token
end