Software-Related Intel

13/12/2009

Creating Shell Commands with Boson + Zsh

Recently, I decided to play around with Boson, a framework for organizing and executing Ruby.  Commands can be executed from both irb and the command line.  Check out the link above as there is a lot of customization available to craft exactly the command library you want.

For example, let’s say I want to post a tweet from the command line.  I create the following module and place it in ~/.boson/commands/


require 'twitter' # twitter gem

module Twitterr

# module named Twitterr to avoid naming clash with twitter gem

def tweet(message)

httpauth = Twitter::HTTPAuth.new('dev_ajw', 'not_my_password')

client = Twitter::Base.new(httpauth)

client.update(message)

end

end

Now, I can post a tweet from the command line:

or from irb:

So this is pretty cool.  Not only can Boson be used to organize helper functions for use in irb, but new command line functions can be written using pure Ruby.  Now, if only I didn’t have to type ‘boson’ before each command.

Zsh’s command_not_found_handler

Turns out zsh contains a function similar to Ruby’s method_missing.  If you define command_not_found_handler(), this function will be called when a command is not recognized.  So I drop this in ~/.zlogin:

command_not_found_handler() {
boson $*
}

and any command not recognized by the shell will be forwarded to Boson.  Now, the tweet command can be called directly from the command line:

One possible side effect is the additional time taken to scan the Boson modules for every unknown command.  So far, this hasn’t bothered me.  I’ll see if things change as my Boson library grows.

Comments
blog comments powered by Disqus
Tumblr » powered Sid05 » templated