[英]Saving multiple api response in a single object in Ruby
I have a scenario where I need to convert multiple API responses into one object.我有一个场景,我需要将多个 API 响应转换为一个 object。 Is it possible how?怎么可能? Below is my code.下面是我的代码。 How do I convert it into one single object?如何将其转换为单个 object?
require 'httparty'
require 'json'
def make_request(url)
HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response
end
numberone_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code}&cnt={cnt}&appid={API key}')
numbertwo_apis= make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code},{country code}&cnt={cnt}&appid={API key}')
numberthree_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={API key})
puts numberone_apis
puts numbertwo_apis
puts numberthree_apis
convert_object2one = how ?
Due to missing information on how the single responses look I can only recommend to build a new object.由于缺少有关单个响应外观的信息,我只能建议构建一个新的 object。 This answer is not optimized and highly opinionated based on the small given information.根据给定的小信息,这个答案没有优化和高度固执己见。
require 'httparty'
require 'json'
def make_request(url)
HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response
end
whole_response = {}
whole_response['numberone_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code}&cnt={cnt}&appid={API key}')
whole_response['numbertwo_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code},{country code}&cnt={cnt}&appid={API key}')
whole_response['numberthree_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={API key}')
puts whole_response
#=>
{
'numberone_apis':
{ ... },
'numbertwo_apis':
{ ... },
'numberthree_apis':
{ ... }
}
One way to do this would be to make a class that represents what this object.一种方法是制作一个 class 来代表这个 object。 To get this to work you need a good name.要让它发挥作用,你需要一个好名字。 Perhaps something like也许像
class WeatherReport
def initialize(...
get_data
assemble
end
def get_data
make_first_request
...
end
def make_first_request
@first_response = make_request('api ...
end
...
def assemble
# add the responses together
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.