Thursday, January 29, 2009

Active-support-for-javascript

The focus is to extend the language, modifying the base classes to add several handy methods and shortcuts. It works on top of Prototype and extends the core classes somewhat to the same extent than ActiveSupport extends ruby's core to make a lot of stuff pretty.

For example, you can do things like:

  (10).minutes().fromNow()             //=> Date object ten minutes in the future
"person".pluralize() //=> "people"
["dog", "cat", "mouse"].toSentence() //=> "dog, cat and mouse"
Date.now().strftime("It's %H:%M") //=> "It's 16:23"

Plus several other stuff, like string interpolation (a la Ruby), so you get:

  var name = "johnny";
$Q("Hello, my name is #{name.capitalize()}"); //=> "Hello, my name is Johnny

And you can even interpolate inside objects! For example, let's suppose you have the following class:

  var Dog = Class.create();
Dog.prototype = {
initialize: function(name) { this.name = name; },
woof: function() { return "woof!"; }
}

var bobby = new Dog("bobby");

You can use interpolation inside the class passing the binding to $Q as a second parameter :

  Dog.prototype.greet = function() {
$Q("I'm #{this.name} and I #{this.woof()}", this); //=> "I'm bobby and I woof!"
}

Or you can do this even outside classes:

  $Q("It's #{this.getMinutes()} after #{this.getHours()}", new Date());

So whatever you pass to $Q on the second parameter becomes what "this" points to inside the strings.

http://code.google.com/p/active-support-for-javascript/

No comments: