URI :: InvalidURIError使用HTTParty时

时间:2015-02-26 14:11:53

标签: ruby sinatra httparty

我按照HTTParty github page中的一个例子提出了这个问题:

class MatchHistory
    include HTTParty
    base_uri = "api.steampowered.com/IDOTA2Match_570"

    def initialize
        @options = { query: { key: STEAM_API_KEY } }
    end

    def latest
        self.class.get("/GetMatchHistory/V001", @options)
    end
end

get '/' do 
    history = MatchHistory.new

    history.latest.body
end

我收到以下错误:

URI::InvalidURIError at /
the scheme http does not accept registry part: :80 (or bad hostname?)

但是,当我使用如下的更简单的解决方案时,它会很好地返回结果:

class MatchHistory
    def initialize
        @base_uri = "http://api.steampowered.com/IDOTA2Match_570"
    end

    def latest
        HTTParty.get(@base_uri + "/GetMatchHistory/V001/?key=" + STEAM_API_KEY)
    end
end

1 个答案:

答案 0 :(得分:3)

base_uri是一个类方法,因此您应该在类中定义它,而不是在初始化器中定义它。您可以在您提供的链接的第一个示例中看到它。

class MatchHistory
    include HTTParty

    base_uri "api.steampowered.com/IDOTA2Match_570"

    def initialize
        @options = { query: { key: STEAM_API_KEY } }
    end

    def latest
        self.class.get("/GetMatchHistory/V001", @options)
    end
end