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 %> |
Appreciate that @phoet, thanks a lot :)
Would it be possible to tuck away Amazon API keys and values somewhere...
Build the request in a private method or, if you're so inclined, extract to a class.
To parse the response, you have a few options. If you just want to transform the hash to a Ruby-esque data container, throw it into Rash. Or write a small parser using Nokogiri or Ox. Latter will be more performant, if that matters.
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.)
class MainController < ApplicationController
def index
ThirdPartyProducts.fetch 'Books', 'Ruby on Rails'
end
end
class ThirdPartyProducts
def self.fetch category, topic
AmazonProducts.fetch(category, topic) +
SomeOtherStore.fetch(category, topic)
end
end
class ThirdPartyProducts::AmazonProducts
ACCESS_KEY_ID: 'ABCDEFGHIJKLMNOPQRST',
SECRET_ACCESS_KEY: '<long messy key>',
ASSOCIATE_TAG: 'lipsum-20'
# or better yet, put these in environment variables
# and read the using env['ACCESS_KEY_ID'] as
# proposed in the vacuum Readme
def self.fetch category, topic
# all your product fetching logic here
end
end
This is better because:
Niko.
i don't think that porting it to asin will help you in any way. if you feel like spending some time on digging into it you can see a working demo here: http://asin.herokuapp.com/