ライド・オン・Rails
ですが、面白そうなので、リファレンス系のページはばっさり飛ばして、「Amazon Webサービスとの連携」やってみます。
本ではruby-amazonを使っての説明ですが、ちょっと調べると、amazon-ecs がよさげ。gemで簡単にインストールできます。
gem install amazon-ecs
そうするとサンプルも書き直さないといけない。こんな感じか。
def amazon_search
@books = []
if request.post?
require 'rubygems'
require 'amazon/ecs'
access_key = "your access key"
associate_id = "your associate id"
country = :jp
Amazon::Ecs.options = {
:aWS_access_key_id => [access_key],
:associate_tag => [associate_id],
:country => country
}
res = Amazon::Ecs.item_search(params[:keyword], {
:search_index => 'Books',
:sort => 'salesrank',
:response_group => 'Medium'
}
)
if res.has_error?
flash[:notice] = "Amazon ECSよりエラー:" + res.error
return
end
res.items.each do |item|
book = Book.new
book.isbn = item.get('isbn')
book.name = item.get('title')
book.author = item.get('author')
smallimage = item.get_hash('smallimage')
if smallimage
book.small_img_url = smallimage[:url]
else
book.small_img_url = 'noimage.gif'
end
book.manufacturer = item.get('publisher')
book.release_on = item.get('publicationdate')
@books.push book
end
end
本ではruby-amazonが返すオブジェクトをそのまま使ってビューをレンダリングしてるが、amazon-ecsはイメージURLの持ち方が単純でないので、Bookモデルに詰め替えることにします。small_img_urlというフィールドを勝手に追加してます。
この辺、Rubyに慣れてないんでアドホックですが、たぶんそのうちクールな方法を習得するはず。今は一杯一杯。
Ruby Amazon E-Commerce REST Service API (amazon-ecs)によると、
# or you can also do it this way
atts = item.get('itemattributes')
atts.get('title')
# get only returns the first element of an array
atts.get('author') # 'Author 1'
という風に、AmazonのAPIドキュメントAttributes of Items in the Book Storeに忠実に取得できて気持ちいいと思い、使おうとしたのですが、
atts = item.get('itemattributes')
が返すオブジェクトがgetメソッドがないと仰る…それで色々と試した結果、itemオブジェクトから直接getはできる様なのでそっちでやりました。
そして、これを表示するビューは、こんな感じか、
<%= form_tag %>
keyword: <%= text_field_tag 'keyword', params[:keyword] %>
<%= submit_tag 'search' %>
<%= end_form_tag %>
<table>
<tr>
<th>ISBN</th>
<th>authors</th>
<th>image (small)</th>
<th>manufacturer</th>
<th>product_name</th>
<th>release_date</th>
</tr>
<% @books.each do |book| -%>
<tr>
<td><%=h book.isbn %></td>
<td><%=h book.author %></td>
<td><%=image_tag book.small_img_url %></td>
<td><%=h book.manufacturer %></td>
<td><%=h book.name %></td>
<td><%=h book.release_on %></td>
</tr>
<% end -%>
</table>
まだまだ拙いが、なんとなく分ってきたかな。
早くRuby on Railsを自由自在に使いこなしてアプリを作り始めたいのだが、そうこうしているうちに大連休の最終日夕方(死)
やはり、そう甘くはないと言うことで(笑)しかしRuby on Railsはこの先、相当な武器になりそうなので、やっていく。
コメントする