ruby-on-rails - 如何重构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}×tamp=#{@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}×tamp=#{@time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}"
“参数”方法并将其传递给该RestClient.get
方法。
解决方案
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
推荐阅读
- javascript - 组件无法从 Vue 实例调用方法 v-on:click
- python - Python以给定的索引跳转或更少的方式递归地跳过列表,同时避免零
- c - 选择排序:什么是n-1?
- c++ - boost::interprocess 消息队列未删除
- node.js - 将 process.hrtime() 转换为毫秒
- java - 如何从插件覆盖 Cordova 项目的 gradle.properties?
- ms-access - Access 2016 中的序列号
- laravel - 我如何在 Laravel 上使用 Queue::after?
- r - 内存不足文件的汇总统计信息
- php - 如何同时使用 php7 和 php8?