2013-08-28 26 views
0

我正在使用亚马逊产品广告API,并且在我的控制器中修改其响应以呈现自定义的JSON,但其响应会根据产品类别而改变很多,所以我需要编写能够捕获所有它改变的方式。我只需要一些数据,那么如何在将这些数据包含在我自己的自定义JSON中之前,简单地检查这些数据是否存在于Amazon的API响应中?Rails - 如何在添加到新对象之前检查是否已定义?

注意:我使用this gem与Amazon的API集成。它在它自己的对象中返回API响应。

@results = (Amazon's API response) 
@custom_response = [] 
@results.items.each do |product| 
     @new_response = OpenStruct.new(
         :id => product.asin, 
         :source => "amazon", 
         :title => product.title, 
         :price => @product_price, 
         :img_small => @images[0], 
         :img_big => @images[1], 
         :category => product.product_group, 
         :link => "http://amazon.com/") 
     @custom_response << @new_response 
end 

回答

1

你可以尝试这样的: -

@new_response = OpenStruct.new(:source => "amazon", :link => ".....") 

@new_response.id = product.asin if product.asin.present? 
@new_response.title = product.title if product.title.present? 
other attributes....    
相关问题