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/f02239bd3c53cc938ec2 to your computer and use it in GitHub Desktop.
Save frankie-loves-jesus/f02239bd3c53cc938ec2 to your computer and use it in GitHub Desktop.

How come this works

third_party_products.rb (excerpt)
response = client.search(category)

raw_products = JSON.parse(response)["products"]

raw_products.map do |product|
  product = OpenStruct.new(product)
  image = product.images.find { |i| i["sizeName"] == 'Large' }
  product.image = OpenStruct.new(image)
  product
end
main_controller.rb
class MainController < ApplicationController
  def index
    @products = ThirdPartyProducts.fetch 'women'
  end
end
index.html.erb
<h1>Products from the ShopSense API</h1>
<% if @products.any? %>
  <% @products.each do |product| %>
    <div class="product">
      <%= link_to image_tag(product.image.url), product.url %>
      <%= link_to product.name, product.url %>
    </div>
  <% end %>
<% end %>

But not this?

third_party_products.rb (excerpt)
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
main_controller.rb
class MainController < ApplicationController
  def index
    @products = ThirdPartyProducts.fetch 'Books', 'Ruby on Rails'
  end
end
index.html.erb
<h1>Products from Amazon Product Advertising API</h1>
<% if @products.any? %>
  <% @products.each do |product| %>
    <div class="product">
      <%= link_to image_tag(product.image_url), product.url %>
      <%= link_to product.name, product.url %>
    </div>
  <% end %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment