Vacuum with Rails
Goal: Displaying products from the Amazon Product Advertising API.
Goal: Displaying products from the Amazon Product Advertising API.
class MainController < ApplicationController | |
def index | |
request = Vacuum.new('GB') | |
request.configure( | |
aws_access_key_id: '', | |
aws_secret_access_key: '', | |
associate_tag: '' | |
) | |
params = { | |
'SearchIndex' => 'All', | |
'Keywords'=> 'women', | |
'ResponseGroup' => "ItemAttributes,Images" | |
} | |
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 | |
end | |
end |
<h1>Products from the Amazon 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 %> |
If you ask me the controller is completely the wrong place for the API request stuff. Think about how you'd want to issue these API requests in you controller and then build the code to do just that. Like:
(consider this to be pseudo code. never ran. never tested.)
This is better because:
Niko.