2011-09-10 122 views
2

我試圖訪問使用url格式的服務。 www.example.com/api/API_KEY/action在HTTP協議中使用api密鑰

下面的代碼是我試圖實現的一個小例子。

require 'httparty' 

class MyAPI 
    include HTTParty 
    debug_output $stdout 

    base_uri "example.com/api/#{@api_key}" 

    def initialize(api_key) 
    @api_key = api_key 
    end 

    def statistics 
    return self.class.get("/statistics") 
    end 
end 

服務器請求:

MyAPI.new('apikey').statistics 

出來作爲

GET /api//statistics 

我知道這是樂觀的,但我把API_KEY變量在base_uri。我該如何讓網址使用動態api_key?

回答

3

您缺少@api_key的閱讀器方法。

將以下內容添加到您的課程中,以允許在初始化後設置@api_key。

attr_accessor :api_key 

或添加以允許它被讀取,但以後不會設置。

attr_reader :api_key