This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Finding Photos on Flikr
CodeExpectedActual
require 'open-uri'
require 'rexml/document'
require 'cgi'
FLICKR_API_KEY = 'Your API key here'
def flickr_call(method_name, arg_map={}.freeze)
  args = arg_map.collect {|k,v| CGI.escape(k) + '=' + CGI.escape(v)}.join('&')
  url = "http://www.flickr.com/services/rest/?api_key=%s&method=%s&%s" %
    [FLICKR_API_KEY, method_name, args]
  doc = REXML::Document.new(open(url).read)
end
def pick_a_photo(tag)
 doc = flickr_call('flickr.photos.search', 'tags' => tag, 'license' => '4',
                   'per_page' => '1')
 photo = REXML::XPath.first(doc, '//photo')
 small_photo_url(photo) if photo
end
def small_photo_url(photo)
 server, id, secret = ['server', 'id', 'secret'].collect do |field|
   photo.attribute(field)
 end
 "http://static.flickr.com/#{server}/#{id}_#{secret}_m.jpg"
end
pick_a_photo('elephants')
http://static.flickr.com/32/102580480_506d5865d0_m.jpg
Error! (Exception?) Here's stdout:
URI::InvalidURIError: bad URI(is not URI?): http://www.flickr.com/services/rest/?api_key=Your API key here&method=flickr.photos.search&license=4&tags=elephants&per_page=1
	from /usr/lib/ruby/1.8/uri/common.rb:432:in `split'
	from /usr/lib/ruby/1.8/uri/common.rb:481:in `parse'
	from /usr/lib/ruby/1.8/open-uri.rb:85:in `open'
	from (irb):9:in `flickr_call'
	from (irb):12:in `pick_a_photo'
	from (irb):23
pick_a_photo('what-will-happen-tomorrow')
nil
Error! (Exception?) Here's stdout:
URI::InvalidURIError: bad URI(is not URI?): http://www.flickr.com/services/rest/?api_key=Your API key here&method=flickr.photos.search&license=4&tags=what-will-happen-tomorrow&per_page=1
	from /usr/lib/ruby/1.8/uri/common.rb:432:in `split'
	from /usr/lib/ruby/1.8/uri/common.rb:481:in `parse'
	from /usr/lib/ruby/1.8/open-uri.rb:85:in `open'
	from (irb):9:in `flickr_call'
	from (irb):12:in `pick_a_photo'
	from (irb):24