Tuesday 3 April 2012

Searching Flickr using the Flickraw gem

The more I look at Ruby, the more I appreciate just how powerful and succinct  it is. I'm sure my current Ruby coding style isn't yet close to The Ruby Way,but I'll keep working on that. In the meantime, I wrote this script over lunch, in preparation for a Rails application I have in mind. The script searches flickr for photos tagged with a word you supply as a command line argument, then picks a random one and launches the browser to display it. You'll need both the Flickraw and Launchy gem installed for this script to run. You'll also need a flickr API key, which you can apply for here.


Install required gems:
 gem install flickraw  
 gem install launchy  
The code:
 #!/usr/bin/env ruby  
 require 'flickraw'  
 require 'launchy'  
 FlickRaw.api_key    = 'YOUR_API_KEY_HERE'  
 FlickRaw.shared_secret = 'YOUR_SHARED_SECRET_HERE'  
 results = flickr.photos.search(:tags => ARGV[0])  
 rand = Random.new.rand(results.length)  
 info = flickr.photos.getInfo(:photo_id => results[rand].id)  
 url = FlickRaw.url_b(info)  
 Launchy.open(url)  
 (replace YOUR_API_KEY_HERE and  YOUR_SHARED_SECRET_HERE with your information from flickr)


Save this as flickr_single_tag.rb, and then run it, supplying a single search tag on the command line:
 ruby flickr_single_tag.rb surf  


Last time I ran it (with surf, as above), I got the image below. It's kind of fun to see what kind of images the returns! 





This gist contains the code from this post. 

No comments:

Post a Comment

Please leave a comment if you find this blog helpful or interesting! I'd love to hear from you!