module Asterisk
  class Client
    include HTTParty
    base_uri 'https://asterisk.dev/'

    def initialize(session_key = nil)
      @session_key = session_key
    end

    def get_session_key(login, password)
      self.class.put('/api/auth', query: { login: login, password: password })
    end

    def get_contacts
      self.class.get("/api/#{@session_key}/contacts")
    end

    def get_contact(id)
      self.class.get("/api/#{@session_key}/contact/#{id}")
    end

    def create_contact
      self.class.put("/api/#{@session_key}/create")
    end

    def logout
      self.class.delete("/api/#{@session_key}/logout")
    end
  end
end

现在它的工作原理如下
session_key = Asterisk::Client.new.get_session_key('login', 'pass')
client = Asterisk::Client.new(session_key)
client.get_contacts

我想使用singleton获取和设置会话密钥。怎么做?

最佳答案

module Asterisk
  class Client
    include HTTParty
    include Singleton
    base_uri 'https://asterisk.dev/'

    attr_reader :last_session_update

    private

    def session_key
      if !@session_key || session_refresh_needed?
        @session_key = set_session_key
        @last_session_update = Time.now
      else
        @session_key
      end
    end

    def set_session_key
      self.class.put('/api/auth', query: { login: login, password: password })
    end

    def password
     #the way you get pass
    end

    def login
     #the way you get login (ENV...)
    end

    def session_refresh_needed?
      return true unless last_session_update
      ( Time.now - last_session_update) > 30.minute
    end
  end
end

它包括你的问题与30分钟刷新。
现在呼叫Asterisk::Client.instance

09-28 04:48