Skip to content

Instantly share code, notes, and snippets.

@frankie-loves-jesus
Last active August 29, 2015 14:04
Show Gist options
  • Save frankie-loves-jesus/4f4925b938f837da892e to your computer and use it in GitHub Desktop.
Save frankie-loves-jesus/4f4925b938f837da892e to your computer and use it in GitHub Desktop.

Beautify the parsing of API response using Hashie Rash

Amazon API

Before

raw_products = request.item_search(query: params)
hashed_products = raw_products.to_h
 
@products = []
  
hashed_products['ItemSearchResponse']['Items']['Item'].each do |item|
  product = OpenStruct.new
  product.name = item['ItemAttributes']['Title']
  product.url = item['DetailPageURL']
  product.image_url = item['LargeImage']['URL']
  
  @products << product 
end

After (wild guess)

raw_products = request.item_search(query: params)
@products = Hashie::Rash.new(raw_products.to_h)

@products.item_search_response.items.item.each do |item|
  product = OpenStruct.new
  product.name = item['item_attributes']['title']
  product.url = item['detail_page_url']
  product.image_url = item['large_image']['url']
  
  @products << product 
end

Result

undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment