Created
April 30, 2010 20:02
-
-
Save leandro/385679 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require 'json' | |
| require 'hpricot' | |
| require 'open-uri' | |
| module Rublickr | |
| 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 at least an api_key: a = Rublickr::Flickr.new('your_api_key', nil, :format => json) | |
| # 2) makes an API call: b = a.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) | |
| class Flickr | |
| attr_reader :options, :api_key, :api_secret | |
| # 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 = {}) | |
| @api_key = api_key | |
| @api_secret = api_secret | |
| @options = options | |
| @meth = ['flickr'] | |
| @http_response = nil | |
| end | |
| def method_missing(method, *args) | |
| methstr = method.id2name | |
| @meth << methstr | |
| return self if args.empty? | |
| api_method = @meth.join('.') | |
| @meth = ['flickr'] | |
| get_response(api_method, @options.merge(args.first)).to_response | |
| 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 = xml.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