Created
December 15, 2009 19:54
-
-
Save rbxbx/257239 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# MothrFlickr, a small and light wrapper for talking to Flickr's API | |
require 'json' | |
require 'net/http' | |
module MothrFlickr | |
#put your API Key in config/mothr_flickr.yml | |
module Responsable | |
def base_path | |
@base_path ||= "/services/rest/?api_key=#{MothrFlickr.api_key}" | |
end | |
def hashed_response(method, params={}) | |
JSON.parse( | |
rest_response(method, params.merge(:format => "json")).body[14..-2] | |
) | |
end | |
def rest_response(method, params={}) | |
Net::HTTP.get_response("api.flickr.com", | |
"#{base_path}&method=#{method}&#{params.to_param}") | |
end | |
end | |
class Photo | |
include Responsable | |
SIZES = { | |
:thumb => 't', | |
:square => 's', | |
:small => 'm' | |
} | |
attr_accessor :id, :secret, :server | |
def initialize(photo_hash) | |
self.id, self.secret, self.server = photo_hash['id'], | |
photo_hash['secret'], | |
photo_hash['server'] | |
end | |
def url(size=:thumb) | |
"http://farm4.static.flickr.com/#{server}/#{id}_#{secret}_#{SIZES[size]}.jpg" | |
end | |
end | |
class Photoset | |
include Responsable | |
attr_accessor :id, :secret, :server, :title, :description, :photos | |
def initialize(id) | |
self.id = id | |
end | |
def get_photos | |
photoset = hashed_response("flickr.photosets.getPhotos", :photoset_id => id)['photoset'] | |
photoset['photo'].map { |photo| Photo.new(photo) } | |
end | |
def photos | |
@photos ||= get_photos | |
end | |
def photo_urls(size=:square) | |
photos.map { |photo| photo.url(size) } | |
end | |
end | |
class User | |
include Responsable | |
attr_accessor :nsid, :username | |
def initialize(username) | |
self.username = username | |
end | |
def get_photosets | |
photosets = hashed_response("flickr.photosets.getList", :user_id => nsid)['photosets'] | |
photosets['photoset'].map { |photoset| Photoset.new(photoset['id']) } | |
end | |
def nsid | |
@nsid ||= lookup(username)['user']['id'] | |
end | |
def photosets | |
@photosets ||= get_photosets | |
end | |
private | |
def lookup(username) | |
hashed_response("flickr.urls.lookupUser", | |
:url => "http://www.flickr.com/people/#{username}") | |
end | |
end | |
def self.api_key | |
@api_key ||= YAML.load_file("#{RAILS_ROOT}/config/mothr_flickr.yml")['api_key'] | |
end | |
Hash.class_eval do | |
def to_param | |
self.map{ |k,v| "#{k}=#{v}" }.join("&") | |
end | |
end unless Object.const_defined?(:Rails) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment