Created
November 11, 2009 11:55
-
-
Save spp/231887 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
| # To change this template, choose Tools | Templates | |
| # and open the template in the editor. | |
| class Bitly < ActiveResource::Base | |
| self.site = 'http://api.bit.ly' | |
| self.user = 'USERNAME' | |
| self.password = 'PASSWORD' | |
| cattr_accessor :login, :return_format, :api_key, :bitly_version | |
| self.login = 'USERNAME' | |
| self.api_key = 'R_your_api_key_here' | |
| self.return_format = 'xml' | |
| self.bitly_version = '2.0.1' | |
| def self.shorten(long_url) | |
| return long_url if long_url.length <= 20 | |
| begin | |
| resp = find(:one, | |
| :from => "/shorten", | |
| :params => { | |
| :longUrl => long_url, | |
| :login => @@login, | |
| :apiKey => @@api_key, | |
| :version => @@bitly_version, | |
| :format => @@return_format | |
| } | |
| ) | |
| # If response does not respond_to results, it means the XML format is incorrect. | |
| # In future, when bitly change their return xmls, all we have to do is update these two lines. | |
| raise ArgumentError unless resp.respond_to?("results") && resp.results.respond_to?("nodeKeyVal") | |
| resp.results.nodeKeyVal.shortUrl | |
| rescue ActiveResource::TimeoutError, ArgumentError | |
| # Return the long_url since we didn't get a shortened url. | |
| long_url | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment