Amazon APIからのデータ取得 – ca007
■API Key他の初期設定
Ruby
# ---- cpro01\config\environment.rb ----
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
# amazon-ecs
require 'amazon/ecs'
Amazon::Ecs.debug = true
Amazon::Ecs.options = {
:aWS_access_key_id => "foo",
:associate_tag => "bar-22",
:country => :jp,
:aWS_secret_key => "baz"
}
end
▲44~52行目を追加
■Modelの生成
ファイルのみ作成(generaterで生成するとActiveRecordを継承するため、利用しない)
Ruby
# ---- cpro01\app\models\item.rb ----
class Item
attr_accessor :asin, :title, :url, :image, :author
def initialize(asin, title = nil, url = nil, image = nil, author = nil)
@asin = asin
@title = title
@url = url
@image = image
@author = author
end
end
■BooksControllerの編集
searchメソッドを作成し、Amazon APIからデータを取得する。
Ruby
# ---- cpro01\app\controllers\books_controller.rb ----
class BooksController < ApplicationController
# GET /books
# GET /books.xml
def index
@books = Book.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @books }
end
end
# GET /books/1
# GET /books/1.xml
def show
@book = Book.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @book }
end
end
# GET /books/new
# GET /books/new.xml
def new
@book = Book.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @book }
end
end
# GET /books/1/edit
def edit
@book = Book.find(params[:id])
end
# POST /books
# POST /books.xml
def create
@book = Book.new(params[:book])
respond_to do |format|
if @book.save
flash[:notice] = 'Book was successfully created.'
format.html { redirect_to(@book) }
format.xml { render :xml => @book, :status => :created, :location => @book }
else
format.html { render :action => "new" }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity }
end
end
end
# PUT /books/1
# PUT /books/1.xml
def update
@book = Book.find(params[:id])
respond_to do |format|
if @book.update_attributes(params[:book])
flash[:notice] = 'Book was successfully updated.'
format.html { redirect_to(@book) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.xml
def destroy
@book = Book.find(params[:id])
@book.destroy
respond_to do |format|
format.html { redirect_to(books_url) }
format.xml { head :ok }
end
end
def search
#キーワード取得
@keyword = params[:keyword]
#検索用初期値
@search_index = "Books"
@sort = "daterank"
#検索
res = Amazon::Ecs.item_search(@keyword, {
:search_index => @search_index,
:response_group => 'Medium',
:sort => @sort
})
@items = []
res.items.each do |item|
@items << Item.new(
item.get('asin'),
item.get('itemattributes/title'),
item.get('detailpageurl'),
item.get_hash('smallimage'),
item.get('author')
)
end
end
end
▲88~112行目を追加
■Viewファイルの作成
search.html.erbを手動で新規作成。
Ruby
<%# ---- cpro01\app\views\books\search.html.erb ---- %>
<p>検索結果</p>
<% if @items && @items.size > 0 %>
<table>
<% @items.each do |item| %>
<tr>
<td><%= item.title %><br />
<% if item.image != nil %>
<%= link_to(image_tag(item.image[:url], :size => "#{item.image[:width]}x#{item.image[:height]}", :alt => item.title), item.url, :target => '_blank') %>
<% end %><br />
<%= item.asin %><br />
<%= item.author %>
</td>
</tr>
<% end %>
<% end %>
</table>
■検索用キーワード入力欄を追加
topのindex.html.erbに追加
Ruby
<% # ---- cpro01\app\views\top\index.html.erb ---- %> <h1>Top#index</h1> <p>Find me in app/views/top/index.html.erb</p> <%= @gmap.div(:width => 550, :height => 400) %> <p>Amazonから登録図書を検索</p> <% form_tag :controller => 'books', :action => 'search' do %> タイトル:<%= text_field_tag "keyword", @keyword %><br /> <%= submit_tag "アマゾンで検索" %><br /> <% end %>
▲7~11行目を追加
zo-i | Project004:cpro01 | 01 11th, 2010 |