Listing 2. combined-lookup.rb #!/usr/bin/ruby require 'net/http' require 'rexml/document' if ARGV.length == 0 puts "#{$0}: You must enter at least one argument." exit end output = "" # Set up our regular expressions not_in_collection_re = /class="yourEntryWouldBeHereData"/ix on_shelf_re = /CHECK\s+SHELF/ix checked_out_re = /DUE /ix # Iterate through each of our arguments ARGV.each do |isbn| # Ignore non-ISBN arguments if not isbn.match(/[0-9xX]{10}/) output << "ISBN #{isbn} is invalid.\n" next end output << "ISBN: #{isbn}\n" # ------------------------------------------------------------ # Amazon # ------------------------------------------------------------ # Put together an Amazon parameter string amazon_params = {'Service' => 'AWSECommerceService', 'Operation' => 'ItemLookup', 'AWSAccessKeyId' => 'XXX', 'ItemId' => isbn, 'ResponseGroup' => 'Medium,OfferFull', 'MerchantId' => 'All'}.map {|key,value| "#{key}=#{value}"}.join("&") # Ask Amazon what it knows about our ISBN amazon_response = Net::HTTP.get_response('webservices.amazon.com', '/onca/xml?' << amazon_params) xml = REXML::Document.new(amazon_response.body) # Get the lowest new, used, and collectible prices new_price = xml.root.elements["Items/Item/OfferSummary/LowestNewPrice/FormattedPrice"] if new_price.nil? output << "\tNew: None available\n" else output << "\tNew: #{new_price.text}\n" end used_price = xml.root.elements["Items/Item/OfferSummary/LowestUsedPrice/FormattedPrice"] if used_price.nil? output << "\tUsed: None available\n" else output << "\tUsed: #{used_price.text}\n" end collectible_price = xml.root.elements["Items/Item/OfferSummary/LowestCollectiblePrice/FormattedPrice"] if collectible_price.nil? output << "\tCollectible: None available\n" else output << "\tCollectible: #{collectible_price.text}\n" end # ------------------------------------------------------------ # Library # ------------------------------------------------------------ # Ask the library what it knows about our ISBN library_response = Net::HTTP.get_response('catalog.skokie.lib.il.us', "/search~S4/i?SEARCH=#{isbn}") # Check our regular expressions against the HTML response if not_in_collection_re.match(library_response.body) output << "\tLibrary: Not in the Skokie collection.\n" elsif checked_out_re.match(library_response.body) output << "\tLibrary: Checked out.\n" elsif on_shelf_re.match(library_response.body) output << "\tLibrary: On the shelf.\n" else output << "\tLibrary: Unparseable response\n" end end # Show everyone what we've learned puts output