【问题标题】:Saving multiple api response in a single object in Ruby在 Ruby 中的单个对象中保存多个 api 响应
【发布时间】:2021-07-23 15:59:46
【问题描述】:

我有一个场景,我需要将多个 API 响应转换为一个对象。怎么可能?下面是我的代码。如何将其转换为一个对象?

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 ? 

【问题讨论】:

  • 我的第一个想法 - 看看深度合并(或只是合并)。这在很大程度上取决于响应结构和您的预期结果结构。

标签: json ruby hash backend httpbackend


【解决方案1】:

由于缺少有关单个响应外观的信息,我只能建议构建一个新对象。基于少量给定信息,此答案并未优化且高度固执己见。

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':
    { ... }
}

【讨论】:

  • 这可行,但由于缺乏检查响应代码等而注定会失败
  • @gates ye sure... 这个答案是基于 OPs 的问题。也不关心响应状态,所以我为什么要使用 OP 可能已经意识到的其他信息来扩展问题的范围,并将其排除在外,因为它与他的问题无关。
  • 当你说 { --- } @DennyMueller 时,我们可以在第 20 行之间期待什么?
  • @gates 我没想到,谢谢提醒。如果响应失败时需要添加检查,您将如何实现?
【解决方案2】:

一种方法是创建一个类来表示该对象的内容。要让它发挥作用,你需要一个好名字。也许像

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

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多