Sha256: ab030b1d057fc959bcdafe4a5763771c31c3b72746fb611abf510b7345f85b4d

Contents?: true

Size: 855 Bytes

Versions: 3

Compression:

Stored size: 855 Bytes

Contents

# frozen_string_literal: true

require 'active_support/cache'
require 'active_support/cache/memory_store'
require 'active_support/notifications'

module Mpesa
  class Token < Resource
    def token
      if cache.exist?('token')
        expires_at = cache.send(:read_entry, 'token')&.expires_at
        Object.new({
                     "access_token": cache.fetch('token'),
                     "expires_in": expires_at - Time.now.to_f
                   })
      else
        cache_token
      end
    end

    def cache_token
      res = call
      cache.write('token', res.access_token, expires_in: res.expires_in)
      res
    end

    def call
      Object.new get_request(url: 'oauth/v1/generate?grant_type=client_credentials', basic_auth: true).body
    end

    def cache
      @cache ||= ActiveSupport::Cache::MemoryStore.new
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mpesarb-0.3.4 lib/mpesa/resources/token.rb
mpesarb-0.3.3 lib/mpesa/resources/token.rb
mpesarb-0.3.2 lib/mpesa/resources/token.rb