Get Tweets with MooTools

To give this site a little dynamism, I decided (as many others have) to pull my latest tweets into the rather barren sidebar. David Walsh’s TwitterGitter was a good start, but I saw some room for improvement by subclassing Request.JSONP. The result is a great example of how MooTools grants you a great deal of object oriented power. I kept David’s linkify method (with some regex tweaks) because it is awesome.

Request.Twitter = new Class({

  Extends: Request.JSONP,

  options: {
    linkify: true,
    url: '{term}.json',
    data: {
      count: 5
  initialize: function(term, options){
    this.options.url = this.options.url.substitute({term: term});
  success: function(data, script){
    if (this.options.linkify) data.each(function(tweet){
      tweet.text = this.linkify(tweet.text);
    }, this);
    // keep subsequent calls newer
    if (data[0]) = data[0].id;
    this.parent(data, script);
  linkify: function(text){
    // modified from TwitterGitter by David Walsh (
    // courtesy of Jeremy Parrish (
    return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
               .replace(/(^|\W)@(\w+)/g, '$1<a href="$2">@$2</a>')
               .replace(/(^|\W)#(\w+)/g, '$1#<a href="$2">$2</a>');

Hopefully the code speaks for itself. I’ll keep this Gist updated with any bugfixes.

About Me

I'm Scott Kyle, a MooTools developer and Apple addict. You can follow me on Twitter, fork me on GitHub, and check out some of my work on my portfolio.