Writing a jQuery plugin with coffeescript

Coffescript saves my day, as I don’t like javascript and the coffeescript syntax is more python/ruby based. Coffeescript itself compiles to javascript. It is very easy to learn, nevertheless it was not easy to create the basic code to register a new jQuery plugin. The following code serves as template:

1
2
3
4
5
6
7
8
9
10
11
$ = jQuery
 
methods =
  init: (options) ->
    obj = @
    # do something
 
$.fn.your_plugin_name = (method) ->
  if method of methods
    return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
  else $.error( "Method #{method} does not exist on jQuery.your_plugin_name" );

This coffeescript compiles to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var $, methods;
$ = jQuery;
methods = {
  init: function(options) {
    var obj;
    return obj = this;
  }
};
$.fn.your_plugin_name = function(method) {
  if (method in methods) {
    return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  } else {
    return $.error("Method " + method + " does not exist on jQuery.your_plugin_name");
  }
};

You would call your plugin e.g. this way (from javascript):

$('#target_div').your_plugin_name('init', {your: "option"});

If you are still waiting for the *Yeah, I have to use coffeescript!”-moment read this:

The lines of code of my jQuery plugin were reduced by 50% and the code is much more readable now! Don’t miss the coffeescript page which will give you much more arguments for coffeescript as I could ever do here.

Uninstall all local ruby gems

This ruby script might be useful for people like me who just started using bundler to manage the gems of their webapp and all others, which want to clean up their gems. Caution: all installed gems are removed from rubygems!

1
2
3
4
5
6
7
f = open("|gem list")
output = f.read()
 
output.each_line do |l|
	gem_name = l.split(" ").first
	system "gem uninstall --a --ignore-dependencies #{gem_name}"
end

Basically this script just executes the “gem list” command, fetches the output, extracts the gem name and uninstalls it.