3
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

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

4

1 回答 1

2
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

于 2013-09-25T14:05:18.930 回答