Quick Flickr Search In Ruby
Join the DZone community and get the full member experience.
Join For Free// 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
Opinions expressed by DZone contributors are their own.
Comments