Ruby on rails 如何重构ruby rest客户端get方法

Ruby on rails 如何重构ruby rest客户端get方法,ruby-on-rails,ruby,rest-client,Ruby On Rails,Ruby,Rest Client,我正在使用rubysrestclientgem调用googleapi,希望缩短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

我正在使用rubysrestclientgem调用googleapi,希望缩短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客户端gem允许您这样做,但我找不到具体的例子

我想把这个
{@lat}、{@lon}×tamp={@time\u stamp}&key={GOOGLE\u时区\u key}

输入一个“params”方法,并将其传递给
RestClient.get
方法。

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

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

您是否检查了
rest客户端
gem

他们确实给出了一个具体的例子(下面引用自述文件中的例子)

在你的情况下,应该是这样的

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

def params
  {
    locations: "#{@lat},#{@lon}",
    timestamp: @time_stamp,
    key: GOOGLE_TIME_ZONE_KEY
  }
end

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

您能详细说明一下您的问题吗?get已经在您当前的代码中接收到一个uri,并且很可能是可选的参数,到目前为止还没有。
def url
  "https://maps.googleapis.com/maps/api/timezone/json"
end

def params
  {
    locations: "#{@lat},#{@lon}",
    timestamp: @time_stamp,
    key: GOOGLE_TIME_ZONE_KEY
  }
end

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