Archive for the ‘Best Practices’ Category

j (or z) and gr (git root) For Command Line Awesomeness

October 25th, 2011 by Aaron N.

Here’s a little command line utility I use the hell out of:

https://github.com/rupa/z

Basically, this script tracks the directories you cd into on the command line and builds a rank order of their locations. Here’s a chunk of mine (with some fake directory names to protect the innocent):

8.93693 /Users/aaron/Development/mootools-development
17.5369 /Users/aaron/Development/foo
36.132 /Users/aaron/Development/bar
36.6632 /Users/aaron/Development/i/like/cookies
52 /Users/aaron/Development/what/do/we/have/here
97.5176 /Users/aaron/Development
270.192 /Users/aaron/Development/clientcide/Source/Interface
483.024 /Users/aaron/Development/clientcide/Source

If I type “z Source” I’ll automatically jump to that last line because it’s the highest ranked entry that matches that string. “z interface” will take me to the line above it. “z Devel” will take me to the line above that. It’s remarkably smart; it’s very rare that I end up somewhere other than what I want to be, even when I only use one or two characters from the location I’m after (“z clientcide” takes me to clientcide/Source, which may not be what I wanted).

Note: Originally it was called “j” (https://github.com/rupa/j) and I got so used to using that alias that I have “j” aliased to this script. z is the more recent implementation.


Oh, and here’s another one:

alias gr='[ ! -z `git rev-parse --show-cdup` ] && cd `git rev-parse --show-cdup || pwd`'

That command (gr) will take me to the root of any git repo I’m in.

-a

A Portable MooTools Development Environment

September 23rd, 2010 by Aaron N.

The actual process of developing MooTools itself isn’t trivial. It’s not rocket science, but maybe there is a little alchemy involved. For instance, let’s say you want to fix a bug in MooTools More. You fork the library and make the change to fix the bug and now you want to test it. You need MooTools Core for this, but which version? Looking at MooTools Core on Github you see there’s a branch called 1.2x and also a branch called master, not to mention a tag for 1.2.5. MooTools More has several branches, too; there’s master, develop, 1.3wip and others. Which combination of these two libraries work together?

Then you see some test files in the library. Some HTML files that appear to be demos, but they don’t run on their own. You need to install the MooTools Test Runner to view them (you can see an example of it running at review.mootools.net:9876). And then there’s an external specs runner.

If you decide you want to play with MooTools ART you have similar issues, not to mention the widget library – art-widgets – built on top of it.

While it’s true that jsFiddle gives you a sandbox with a lot of these things, it doesn’t give you a working development environment. In an effort to make it easier to share these configurations, I’ve created a portable development environment that makes it relatively easy to get things up and running.

http://github.com/anutron/mootools-development

I’ve made a github repo that has essentially no code and only submodules pointing to all the stuff I use in states that work. In theory, it should make it really easy to reproduce a development environment from scratch. Eventually I’ll configure several different environments. 1.3, 1.2, 1.1, 2.0, whatever.

Right now there are three environments configured. 1.2.5-art-widgets (which includes everything you need to play with art-widgets), 1.3-art-widgets which lets you do the same against MooTools 1.3 (there are some issues that we’re working on so it doesn’t look great at the moment), and 1.2x-tracking-core-more, which includes just mootools-core and mootools-more on their respective 1.2x branches. These are my personal environments and you can use them if you like.

Note that instead of submodules I’m using crepo. One of the reasons is it will allow us to create a version that’s tracking against a branch. For example, the 1.2x-tracking-core-more branch is always tracked against core/master and more/develop. Typing “./go sync” will update to the latest of these two branches.

The result of this means that we can create specific, deployable environments for others and for each other. I could file a lighthouse ticket against -core with a specific state that illustrates a bug in core/1.3 that manifests itself only in art.widgets (which I’ve done – art.sheet is broken in 1.3).

Note that you don’t have to use django to use the environment. My environment includes the test runner that I wrote and depender. But you can just do ./go sync and get all the repos without building the django app.

This doesn’t have to be specific to MooTools, but that’s what I made it for. I don’t see people trying to incorporate this into other tools, though crepo is designed for that purpose (we us it throughout cloudera).

My Talk at JSConf: Programming to Patterns

August 3rd, 2010 by Aaron N.

A few years ago I wrote a post after visiting the Ajax Experience about Programming to Patterns. The JSConf team was nice enough to bring me out to DC to give a talk, which you can watch below, and you can get the slides in PDF or Keynote format here.

How to “Pay it Back” to MooTools

August 7th, 2009 by Aaron N.

I get a lot of emails and tweets saying how awesome MooTools is. Sometimes people want to donate money or give us credit on their work in some way. Others ask how they can contribute. If you want to “pay it back” to MooTools, you can do so by:

We don’t need credit in any overt manner. Your work should be all the credit we need. We would much rather see you involved in the community than any other form of gratitude.

Using Class.Occlude to Create Singletons

July 13th, 2009 by Aaron N.

In my last article I talk about using an instance of Events to allow for loose coupling of functionality to limit dependencies as well as the use of singletons. There was a comment at the bottom of that article that I thought worth sharing and expounding upon:

I’ve been using Class.Occlude and occluding to document.body when I need a singleton. Works like a charm. – Kris Wallsmith

I thought this was a great idea and thought I’d explain what he means for those of you perhaps unfamiliar with Class.Occlude.

What Class.Occlude Does

Class.Occlude allows you to define a class that is tied to a DOM element (as most are) and to prevent that class from creating more than one instance for that DOM element. If you created a class that, say, validated a form, and you wanted to ensure that the user (the JavaScript user – not a site visitor) of your class didn’t attach two instances of that validator to the same form twice, as doing so would result in, say, a state where it was impossible to submit the form, you could use Class.Occlude to ensure that even if two instances of the form validator were created, only one would do anything. Indeed, the second time you tried to instantiate the validator class you would just be returned the first one. Here’s what it looks like:

var FancyFormValidator = new Class({
  Implements: Class.Occlude,
  property: 'FancyFormValidator',
  initialize: function(form) {
    this.element = $(form);
    if (this.occlude()) return this.occluded;
    //...the rest of  your awesome validation logic
  }
});
var fancyValidator = new FancyFormValidator($('myform'));
var fancyValidator2 = new FancyFormValidator($('myform'));
//fancyValidator === fancyValidator2

Using Class.Occlude to Create Singletons

So what Kris does (per his comment) when he wants an instance of a class but wants to ensure that there is only ever one instance, he occludes the document body. This means that even if you try and create a new instance of that class, if you’ve already created one, you’ll be returned the existing one.

For example:

var SingleFoo = new Class({
  Implements: Class.Occlude,
  property: 'SingleFoo',
  initialize: function(arg1, arg2, etc) {
    this.element = $(document.body);
    if (this.occlude()) return this.occluded;
    //the rest of your stuff goes here
 }
});
var foo1 = new SingleFoo(a1, a2, etc);
var foo2 = new SingleFoo(b1, b2, etc);
//foo1 === foo2

A clever solution, if you ask me.

Singletons and Event Arbiters

June 23rd, 2009 by Aaron N.

I got an email today asking about how I use singletons in my own development environment and I thought I’d post my response for anyone who might find it useful.

Here’s the question:

Whats the best way to define some
code, assign it to a global object and have it run all at once?

I use MooTools server-side quite a bit in my ASP code using JScript
and we have need for global singleton objects to be around (such as
our logger). As there are no clear best practice ways out there of
doing it I’ve started and stuck with something like this:

var LoggerObject = function() {
// Logger code
}

var Logger = new LoggerObject()

which is ok but feels like I’m missing something. How do the pros do
it, whats the advantages/disadvantages to other methods?

Now, for those who aren’t familiar with the concept, a singleton is a class that designed to have only one (or, perhaps, a limited number greater than one) instance. In JavaScript, any object can inherit from any other object and you can’t really prevent this, so in the truest sense of the term, there’s no such thing as a JavaScript singleton.

MooTools gives us a function called “Class” which helps us manage inheritance between objects. Creating an object that is an instance of a class is done with the “new” operator:

var myWidget = new Widget()

If you wanted to create a class and immediately cast it into an instance, you could do the following:

var myInstance = new new Class({...})

The double “new” invokes the function returned by class and returns an object – an instance of that class. There’s rarely a reason to do this. In fact, the only reason I can think of is if you want that class to extend another:

var myInstance = new new Class({
    Extends: SomeOtherClass,
    //new properties go here
});

The problem with this pattern is that it doesn’t really get you much. JavaScript is all about objects, and there are better ways to accomplish this task.

I use objects (as singletons) all the time for my application code (almost never for plugins obviously; those are meant to be extended and instantiated). I often use a “site” object to attach methods and manage state (such as if the user is logged in, their username, etc). I just make this a plain old JavaScript object, like so:

var mySite = {
    login: function(username){ this.username = username; },
    showWelcome: function(){
        $('welcome').set('html', 'Welcome ' + this.username);
    }
};

There’s nothing special here – this is how JavaScript works. It’s important to note that classes in MooTools exist to give us functionality and to let us derive functionality through inheritance. If I create a class called Widget and I later want to make a version called Widget.Ajax, I can extend Widget and add only the ajax parts. With singletons, the whole point is that you aren’t going to create more than one of them.

However, there are some other things that MooTools’ Class gives us, such as mixins (classes that are meant to use Implement to imbue the target class with their properties). Examples here include the Events and Options mixins that give instances methods like setOptions and addEvent. In these cases you can still use the object declaration above and then extend the object:

var mySite = {
    login: function(username){
        this.username = username;
        this.fireEvent('login');
    },
    showWelcome: function(){
        $('welcome').set('html', 'Welcome ' + this.username);
    }
};
$extend(mySite, new Events());

Working this way obviates the need for the clunky “new new Class” pattern and it’s more intelligible in my opinion.

Event Arbiters

Which brings me to a common practice I use when I build applications. When I build a site or application I try to make things as modular as possible. I make it so that my site works without any JavaScript first, then I start adding in the UI goodness with ajax and animations and sortable tables and all that jazz. I also make the JavaScript itself modular. Everything that can be a class I make a class. The stuff that’s left over is the code that instantiates those classes.

But what if the code that instantiates one widget needs to get information from another widget? For instance, what if our Welcome widget needs to know the state of the Login widget? Well, if our Login widget stores it’s state on the mySite object, then the Welcome widget can just inspect that, right? That’s cool; if the page loads and mySite.username is undefined then the Welcome widget knows the user isn’t logged in. All good.

But what happens when that state changes? What happens when the user logs in? Now we need an event – onLogin or something, but that means that Welcome needs to attach itself to Login and now we’ve lost some modularity because we’ve introduced a dependency. Welcome can’t work without Login. In this case, this doesn’t seem like a bad dependency to have – after all, a welcome message without login functionality doesn’t make much sense – but there might be dozens of other widgets that need to do things when the user logs in and we may want those widget to work even if the user doesn’t log in. Further, we may want to load the Login widget only on demand – when the user tries to log in for example. We can’t do that if all our widgets need to attach events to the Login widget.

This is why I make mySite an instance of Events. mySite doesn’t really have any native events per se. Rather, other classes attach events to it and fire events for it. So, in our puzzle above about our Login widget, instead of all the other widgets attaching an onLogin event to Login, they can attach it to mySite, and then our Login widget fires that event not on itself but on mySite:

var mySite = new Events();
var Login = new Class({
    //...login logic and stuff
    loginSuccess: function(username){
        mySite.username = username;
        mySite.fireEvent('login');
    }
});
var Welcome = new Class({
    initialize: function(){
        this.showMessage();
        mySite.addEvent('login', this.showMessage.bind(this));
    },
    showMessage: function(){
        $('welcome').set('html', mySite.username ? 'Welcome ' + mySite.username : 'Please log in');
    }
});

Now our classes are no longer dependent on each other. They are both dependent on mySite but that was always the case. They can each come and go as they wish without really caring about the other. This increased modularity pays off later as your site grows in complexity. Some pages may have some widgets and some may have others. You can attach logic to the mySite object without having to really manage those dependencies.

Exporting Files From Git (similar to SVN export)

April 25th, 2009 by Aaron N.

I use git for just about all my code now. For some of my work, I need to export portions of or all of a git repo into some other location without picking up all the git files themselves. This is the way svn export works. There are two ways I do this. One is using git archive. This command always returns a zipped up copy of the repository, so you have to pipe it over to tar if you want to export files (either that or save the tar file and then in a second command extract it). Here’s my one-line command for taking the archive and sending it to a different location:

git archive HEAD | (cd ~/path/where/I/want/it/ && tar -xvf -)

This will extract the ENTIRE library to the specified path (without the .git files and whatnot).

Sometimes, however, I want to pull out just a portion of the library. git archive always gives you the whole enchilada which kinda sucks, and in this case I use rsync, like this:

rsync path/I/want/to/export/ -ri --del -m --exclude ".*" ~/path/where/I/want/it/ |grep sT

That last bit – the grep sT will limit the output of what I see so that I only see the files that are updated. I use that just to sanity check my export. If I see a TON of stuff go to update a path that already has the library and I know I only changed one file, then I know I got the path wrong.

Clientside Image Compression

April 1st, 2009 by Aaron N.

Over the last year of consulting I’ve done several jobs where I didn’t have access to the images used by the site. In one case it was 3rd party software and I was just enhancing the user experience through JavaScript, in another case the images were created dynamically by the server. In yet another case I worked on a site that had editors uploading photos all the time.

In each of these cases it became apparent that the images were never optimized by the people creating them (or, in the case of the machine, by it). I got inspired by smush.it which was demo-ed at the Ajax Experience last year in Boston and spent some time picking apart PNGCrush (an open source image cruncher) and have put together a rather robust solution in JavaScript.

Introducing the JavaScript PNG Resizing Image Library

The JavaScript PNG Resizing Image Library (a.k.a. JPRIL) is easy to use. Just include the library in your document and it will find all the PNG files on your page and compress them for you. You can also call JPRIL directly on a PNG file (for images loaded by JavaScript after the page loads) like so:

JPRIL('myPngElementId')

It’s that easy.

The Output

JPRIL automatically replaces any PNGs in the document with it’s compressed version, garbage collecting the older, larger version. The images look about the same, but how compressed they are is up to you. You can pass in a second argument which is treated as a percentage for compression. Here are two examples:

jprilfools

Download

The code is of course open for anyone to use. Just click here to download it. Compressed and gzipped it’s only 62K.

Update

Yes, this is an April fool’s joke.

Update Update

…someone actually made it: http://ajaxian.com/archives/javascript-jpeg-encoding

Sly, the Latest CSS Selector Engine

March 25th, 2009 by Aaron N.

There’s been a lot of churn on selector engines in the last six months or so. The jQuery guys released a stand alone library (Sizzle) which was adopted by a lot of other frameworks (it’s now a part of the Dojo Foundation) including Prototype, Dojo, jQuery (obviously) and others.

There was a lot of hullabaloo when MooTools decided not to use it. One of the arguments that Valerio made in his post about that was this:

Let’s face it: every selector engine, every part of our libraries has benefited from the others. Where they diverge is not an indicator of which framework is superior to another. Rather, they are differences in philosophy. If everyone were to use the same, shared codebase, these awesome open source contributions and general advancements will stop, and users wouldn’t be able to choose the approach which works best for them. I don’t want to see that happening.

That notion – that if all the frameworks adopted the same selector engine that both innovation will suffer – was refuted generally by the advocates of everyone using Sizzle. John Resig left a long and thoughtful comment on my post about Sizzle that included this statements:

With so many minds at the table (all the major libraries) it’ll mean that this library will be in front of the majority of JavaScript users, in one way or another. It will be compelled to become faster.

Frankly, not using Sizzle will mean that MooTools will always be playing a game of catch-up. … Right now jQuery, Prototype, Dojo, and YUI are all looking at using the library – that only leaves one odd library out. I’m not attempting to put undue pressure on your team – it’s absolutely your decision – but you’ll definitely be in a position, if all the libraries use Sizzle, of constantly trying to catch-up to what is implemented in the de facto implementation.

I refuted this statement and so did members of the MooTools communities (and others). John’s argument that because MooTools is the odd one out that we’ll always be playing catch up seemed especially off the mark, because it implies that Sizzle will, by virtue of having so many people using it and contributing to it, always step ahead of MooTools, and that all MooTools would hope to do is catch up – that is, implement changes to match Sizzle’s progress rather than out pace it. In reality, that’s not how technology moves forward; competing parties take turns passing each other and drive the baseline forward.

Well, today it looks like it’s Sizzle’s turn to play catch up.

Introducing Sly

MooTools contributor Harald Kirschner today released his own selector engine, Sly. This is a stand alone library (much like Sizzle) that is only 3K gzipped (8K minified without gzip). This is on par with Sizzle (which claims that gzipped is 4K). It offers the same sort of flexibility and support for custom selectors plus all the CSS3 selectors. Form the announcement article on Harald’s site.

If you’re a code geek like me, you might want skip the details and go directly to the source, the speed tests or the specs.

Sly awesomeness:

  • Pure and powerful JavaScript matching algorithm for fast and accurate queries
  • Extra optimizations for frequently used selectors and latest browser features
  • Works uniformly in DOM documents, fragments or XML documents
  • Utility methods for matching and filtering of elements
  • Standalone selector parser to produce JavaScript Object representations
  • Customizable pseudo-classes, attribute operators and combinators
  • Just 3 kB! (minified and gzipped, 8 kB without gzip)
  • No dependencies on third-party JS libraries, but developers can override internal methods (like getAttribute) for seamless integration.
  • Code follows the MooTools philosophy, respecting strict standards, throwing no warnings and using meaningful variable names

But what you probably care about most is the performance:

But enough babbling: I know you just want speed and validity results. The following results were measured using a list of frequently used selectors, searching on a copy of yahoo.com, running in slickspeed.

compare2

(See also the DOM fragment speed graph) If you are interested, run the various speed tests on your own system and post your results.

The adapted version of slickspeed also supports other test cases, like querying on a DOM fragment or an XML document. They make sure that Sly and other engines work the same in all environments.

Wait, But This Isn’t MooTools?

That’s right. This is a project Harald was working on and finished and released. This isn’t the official MooTools selector engine and won’t be. MooTools has it’s own new selector engine that is in development. I won’t go into why MooTools isn’t working on a different one (I’ll leave that to its authors to discuss when they are ready to), but the basic point is valid here: having more than one of these things is good competition and it moves the base line forward. Harald’s work has fed directly into the MooTools engine and, perhaps, will also influence Sizzle, who knows.

Why It Kinda Doesn’t Matter

I’ve been saying for a while now that the speed of selector engines is just not an issue any more. The speed of the current selector engines of jQuery, MooTools, and Sly look pretty different on a graph next to each other, but they are all blazing fast. Compared to what they were like a year ago, all of them are miles ahead now and at this point we’re quibbling over milliseconds. There are other things we need to optimize and selector engines are, at this point, plenty fast for nearly all tasks. That’s not to say that there isn’t always room for improvement, but at this point it’s more about features and flexibility than it is speed, and to a great extent all these engines are extensible, flexible, and powerful.

I’m happy to see people out there still cracking this problem open to look at it from fresh perspectives and I’m sure it’s gratifying to write something that performs better than the competition. Congrats to Harald for a fine job well done.

Don’t Repeat Your Moo

March 2nd, 2009 by Aaron N.

There’s a fantastic post over on devthought by MooTools developer Guillermo Rauch that I just had to share.

Given the Object-Oriented nature of the MooTools framework, code repetition is something that is long forgotten (or should be) in the scripts your write. With the avoidance of code repetition comes code reusability, which results in your website being easier to read, extend and maintain, and your scripts smaller in size.

At this point there’s no doubt in anyone’s mind that DRY is a principle we should stick to. However, let’s examine how to achieve this in the right way.