Amazon Web Serviceを使ってISBN-13からASINを取得するRubyプログラム

Amazon Web Servicesを使ってISBN-13からASINを取得するPerlプログラム」をRubyで実装することで勉強させていただこうと思います。

言語仕様が少々違っても、コーディング規約に学ぶ点は多いはず。

ということでAmazon Web ServicesのE-Commerce Serviceを使って、ISBN-13からASINを取得するRubyプログラムを作ってみました。

require 'rexml/document'
require 'open-uri'
require 'kconv'

aws_access_key_id = 'あなたのAccessKeyId'

# For debug
OUTPUT_ENCODING = 'EUC-JP' # 現状意味をなしていません(汗)

# Set up ISBN.
isbn = '9784798111117' #『オブジェクト指向入門 第2版 原則・コンセプト』のISBN-13

# Set up URL.
request_url = 'http://webservices.amazon.co.jp/onca/xml'
option_list = [ 
        "Service=AWSECommerceService",
        "AWSAccessKeyId=#{aws_access_key_id}",
        "Operation=ItemLookup",
        "IdType=ISBN",
        "ItemId=#{isbn}",
        "SearchIndex=Books",
        "ResponseGroup=Request,Small",
        "Version=2007-01-15"
]

# Assemble all options.
option_string = option_list.join('&')
url = "#{request_url}?#{option_string}"

# Retrieve result.
puts "ISBN: #{isbn}"
response_xml = open(url){ |e| REXML::Document.new e }

# Compose output string.
output =<<EOD
ASIN: #{response_xml.root.elements["Items/Item/ASIN"].text}
Title: #{response_xml.root.elements["Items/Item/ItemAttributes/Title"].text}
Author: #{response_xml.root.elements["Items/Item/ItemAttributes/Author"].text}
EOD

print Kconv.toeuc(output)

実行結果です。コマンドラインの都合上EUC-JPにしています。

$ruby amazon_isbn.rb
ISBN: 9784798111117
ASIN: 4798111112
Title: オブジェクト指向入門 第2版 原則・コンセプト
Author: バートランド・メイヤー

というか、PerlのOUTPUT_ENCODINGに相当するRubyの定数が調べきれませんでした…。

これが分かれば、毎回KconvEUCエンコードする必要ないんですけどね。


そして、ここまでやっておきながらトラバで404 Blog Not Foundの中の人が添削をされていました。

perl - 勝手に添削 - isbn2asin


PerlにはURIオブジェクトがあるそうです。

Rubyでもあるのかな?option_listをHashにしてみましたが、結局Stringに変換してるので本質的に上と同じ。

どちらでも結果はもちろん同じです。

option_list = { 
        "Service" => "AWSECommerceService",
        "AWSAccessKeyId" => aws_access_key_id,
        "Operation" => "ItemLookup",
        "IdType" => "ISBN",
        "ItemId" => isbn,
        "SearchIndex" => "Books",
        "ResponseGroup" => "Request,Small",
        "Version" => "2007-01-15"
}
option_string = option_list.map{|key, val| "#{key}=#{val}" }.join('&')

PerlURIみたいなのってRubyにもあるんですかね?