I was writing my own re-tweet class and found that I need to crunch URLs on the fly to make them fit within the 140 character limit on Twitter. Come bit.ly and their API, easily accessible via REST and with a JSONP callback interface, just the job for extending Request.JSONP:
Request.bitly = new Class({ // shorten urls via bit.ly Extends: Request.JSONP, options: { log: !true, bitly: { api: "R_e744c730bdde44a7eacc88cb892074e7", // GET YOUR OWN API KEY login: "webtogs2" // GET YOUR OWN LOGIN }, url: "http://api.bit.ly/v3/shorten?login={login}&apiKey={api}&longUrl={longUrl}&format=json" }, initialize: function(loc, options) { this.parent(options); this.options.bitly.longUrl = loc; this.options.url = this.options.url.substitute(this.options.bitly); }, success: function(data, script) { this.parent(data, script); } });
This is the class, now for the example uses, this will convert all links from the page into bit.ly URLs (if they are shorter than the original)
document.getElements("a").each(function(el) {
new Request.bitly(el.get("href"), {
onSuccess: function(data) {
if (data && data.data && data.status_code == 200) {
var orig = data.data.long_url, hash = data.data.url, difference = orig.length - hash.length;
if (difference > 0) {
el.set({
href: hash,
title: hash + " - saved " + difference + " chars"
}).addClass("shortened");
}
else {
var error = "ERROR:\n your bit.ly hash '" + hash + "' is longer than the original '" + orig + "'";
el.set("html", el.get("html") + error);
}
}
}
}).send();
});
See it all in action on the little jsfilddle here: http://www.jsfiddle.net/dimitar/xVtZy/
GitHub flavoured markdown enabled.