Skip to content

Instantly share code, notes, and snippets.

@leandro
Created October 3, 2010 03:22
Show Gist options
  • Select an option

  • Save leandro/608227 to your computer and use it in GitHub Desktop.

Select an option

Save leandro/608227 to your computer and use it in GitHub Desktop.
require 'json'
require 'hpricot'
require 'open-uri'
module SimpleFlickr
AUTH_URL = 'http://flickr.com/services/auth/'.freeze
API_URL = 'http://api.flickr.com/services/rest/'.freeze
# USAGE
# it's pretty dead simple
# 1) create an instance with a given api_key: flickr = Rublickr::Flickr.new('your_api_key',:format => json)
# 2) makes an API call: flick.photosets.getList(:user_id => '12037949754@N01')
# PS.:
# I didn't implemente authorized calls support yet. Will do soonish.
# I grabbed a piece of code (the xml response dealing from net-flickr gem
# For Flickr API reference visit http://www.flickr.com/services/api/
class Flickr
# attr_reader :options, :api_key, :api_secret
attr_reader :options, :api_key
# I chose to don't give support for auth API calls for now. Will do when necessary.
# def initialize(api_key, api_secret = nil, options = {})
def initialize(api_key, options = {})
@api_key = api_key
# @api_secret = api_secret
@options = options
@meth = ['flickr']
@http_response = nil
end
def call(*args)
api_method = @meth.join('.')
@meth = ['flickr']
self.get_response(api_method, @options.merge(args.first || {})).to_response
end
def method_missing(method, *args)
methstr = method.id2name
@meth << methstr
return self if args.empty?
self.call(*args)
end
def to_response
return nil if @http_response.nil?
begin
if @options[:format] == 'json'
raw_response = @http_response.read[/^(?:[a-z_$][0-9a-z_$]+)?\(?(.*)\)?$/i, 1]
raw_response = raw_response[0..-2] if raw_response[-1].chr == ')'
response = JSON.parse(raw_response)
else
response = Hpricot::XML(@http_response.read)
end
end
if @options[:format].nil? || @options[:format] == 'xml'
unless rsp = response.at('/rsp')
raise 'Invalid Flickr API response'
end
if rsp['stat'] == 'ok'
return rsp
elsif rsp['stat'] == 'fail'
raise rsp.at('/err')['msg']
else
raise 'Invalid Flickr API response'
end
end
response
end
# only non-authorized calls for now
def url_generator(method, params = {})
parameters = parameterize(params)
API_URL + "?" + "method=#{method}&api_key=#{@api_key}" + (parameters.empty? ? '' : "&#{parameters}")
end
def parameterize(params)
params.map {|k,v| "#{k}=#{v}"}.join('&')
end
def get_response(method, params = {})
@http_response = (open(url_generator(method, params)) rescue nil)
self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment