首页 > 解决方案 > 如何重构ruby rest-client get方法

问题描述

我正在使用 Rubys rest-client gem 调用 Google API 并希望缩短 url 部分。

当前代码:

class GoogleTimezoneGetter

  def initialize(lat:, lon:)
    @lat = lat
    @lon = lon
    @time_stamp = Time.new.to_i
  end

  def response
    response = RestClient.get "https://maps.googleapis.com/maps/api/timezone/json?location=#{@lat},#{@lon}&timestamp=#{@time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}"
    JSON.parse(response)
  end

  def time_zone
    response["timeZoneId"]
  end

end

我希望能够做类似的事情:

def response
    response = RestClient.get (uri, params) 
    JSON.parse(response)
end 

但我正在努力寻找如何做到这一点。

为了使课程更整洁,我想将 url 分解为“uri”和“params”。我认为 rest-client gem 允许你这样做,但我找不到具体的例子。

我想将其放入 {@lat},#{@lon}&timestamp=#{@time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}" “参数”方法并将其传递给该RestClient.get方法。

标签: ruby-on-railsrubyrest-client

解决方案


rest-client 已经接受了参数的哈希值。如果您更喜欢类中的一堆小方法,则可以将每个步骤划分为一个方法并保持所有内容的可读性。

class GoogleTimezoneGetter

  def initialize(lat:, lon:)
    @lat = lat
    @lon = lon
    @time_stamp = Time.new.to_i
  end

  def response
    response = RestClient.get gtz_url, params: { gtz_params }
    JSON.parse(response)
  end

  def time_zone
    response["timeZoneId"]
  end

  def gtz_url
    "https://maps.googleapis.com/maps/api/timezone/json"
  end

  def gtz_params
    return {location: "#{@lat},#{@lon}", timestamp: @time_stamp, key: GOOGLE_TIME_ZONE_KEY }
  end
end

推荐阅读