DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Quick Flickr Search In Ruby

02.11.2007
| 4973 views |
  • submit to reddit
        // Examples for the three listed APIs weren't working. Instead of choosing one and debugging it, I chose to do something quick and dirty. "MY_API_KEY" and other params would need to be removed to make this more generic. A naive mapping of API method calls that take hashes, and returns an OpenStruct is an approach I'm considering, as it would likely break less often and require less code.

require 'net/http'
require 'rexml/document'
require 'ostruct'

class Flickr < OpenStruct
  include REXML

  def Flickr.search(text)
    doc = Document.new(
            Net::HTTP.get(
              URI.parse('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY_API_KEY' +
                        '&extras=license,owner_name,original_format&license=4,5&per_page=20&sort=interestingness-desc' +
                        '&text=' + text)))
     throw "flickr error" unless doc.root.attributes['stat'] == "ok"
     doc.root.elements['photos'].get_elements('//photo').collect {|photo| photo << Flickr.new(photo) }
  end

  def initialize(e)
    super(e.attributes)
    self.new_ostruct_member("photo_id")
    self.photo_id = e.attributes['id']
  end

  def to_url(image_type="s")
    "http://farm#{farm}.static.flickr.com/#{server}/#{photo_id}_#{secret}_#{image_type}.jpg"
  end
end