2011-09-10 126 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