【问题标题】:API wrapper in ruby not taking arguments?ruby 中的 API 包装器不接受参数?
【发布时间】:2014-06-26 05:38:53
【问题描述】:

我正在编写一个库来与Elophant API 交互,而我当前的包装器来获取current game infomation 看起来像这样

require "httparty"

class Elophant
    include HTTParty
    base_uri 'api.elophant.com'

    def initialize(name, region)
        @options = {query: {
            summoner_name: name,
            region: region,
            key: ENV["ELOPHANT_API_KEY"]
        }}
    end

    def self.current_game
        HTTParty.get("/v2/#{region}/in_progress_game_info/#{summoner_name}?key=#{key}", @options)
    end

    def self.summoner_info
        HTTParty.get("/v2/#{region}/summoner/#{summoner_name}?key=#{key}", @options)
    end
end

所以我可以打电话

elophant = Elophant.new
elophant.current_game("summoner_name", "OCE")

像这样将这些信息发送到我的 rails 视图

  def index
    elophant = Elophant.new
    @CurrentGame = elophant.current_game("summoner_name", "OCE")
  end

除了 rails 会抛出这个错误

wrong number of arguments (0 for 2)

    base_uri 'api.elophant.com'

    def initialize(name, region)
        @options = {query: {
            summoner_name: name,
            region: region,

【问题讨论】:

  • 你已经用两个参数定义了 Elopant 的初始化器。因此,当您调用 Elopant.new 时,您应该提供名称和区域值。
  • 我认为@options 允许我摆脱我使用的语法?

标签: ruby-on-rails ruby rest httparty


【解决方案1】:

尝试像这样使用Elpohant 类:

elophant = Elophant.new("summoner_name", "OCE")
elophant.current_game

您已将Elophant 定义为在初始化程序中有两个参数,即summoner_nameregion。但是,您在对current_game 的调用中传递了这些信息。

如果在您的情况下,这些参数是方法调用的本地参数,并且可以根据被调用的方法而改变,您可能希望将这些参数带到方法中,即在这种情况下为 current_game

【讨论】:

  • 好吧,我已经完成了,现在它抛出一个错误,说它找不到变量 region 尽管我通过了@options 并且在尝试query.regions 时它说它找不到current_game 方法
  • 好吧,错过了这一点 - current_gamesummoner_info 都是类方法,您是否有理由不希望它们成为实例方法?
  • 好点,虽然尝试def summoner_info 会返回相同的错误
猜你喜欢
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
相关资源
最近更新 更多