-1

我在 lib 方法中有以下 if else 语句:

begin
    url                  = URI.parse("url"+ product )
    @response            = JSON.parse(Net::HTTP.get_response(url).body)
    url2                 = URI.parse("url" + product)
    @response1           = JSON.parse(Net::HTTP.get_response(url2).body)

    if @response != nil
        @url                 = @response["product"]["url"]
        image_url1           = @response["product"]["image_url"]
        @title               = @response["product"]["title"] 

    else
        @url                 = @response1["ProductUrl"]
        @image_url           = @response1["ImagePath"]  
        @title               = @response1["ProductName"]
    end
  rescue 
     next 
end

目前此方法仅检查 url 和 @response,如果 @response = nil 则简单地跳过。如何检查 @response 是否为 nil,如果是,请使用 url2 和 @response1 并保存从该响应返回的变量。如果@response 不为零,则保存从@response 返回的变量。

@response 和 @response1 是不同的 API

4

1 回答 1

2

我想这就是你想要的。关键是要检查 nil,使用 @response.nil? 另一个问题是,如果第一次失败,你会得到相同的 url - 不知道为什么你会再次要求相同的 url,如果第一次失败,你会以不同的方式对待它。

begin
  url = URI.parse("url+ product )
  @response = JSON.parse(Net::HTTP.get_response(url).body)

  if !@response.nil?
    @url = @response["product"]["walmart_canonical_url"]
    @image_url = @response["product"]["image_url"]
    @title = @response["product"]["title"] 
  else
    url = URI.parse("url" + product)
    @response = JSON.parse(Net::HTTP.get_response(url2).body)
    @url = @response["ProductUrl"]
    @image_url = @response["ImagePath"]  
    @title = @response["ProductName"]
  end

rescue
  next
end
于 2013-02-05T00:00:24.287 回答