如何使用singleton重构包装器来设置会话?

时间:2013-09-25 12:46:46

标签: ruby-on-rails ruby api wrapper asterisk

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获取并设置会话密钥。怎么做?

1 个答案:

答案 0 :(得分: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