I just released v0.3.1 of the open_exception gem. This release does a better job of handling exceptions that have been munged by Rails, and now provides a tempfile containing the full stack trace to the open command.

If you are using emacs, you can use the :emacs_with_trace open command, and get the stack trace as a navigable compilation buffer (next to || below) the source file in a split frame. For this to work, you’ll need to add the following function to your emacs init:

See github for the code and README.

open_exception opens an exception in your favorite editor when developing locally. It works by parsing the backtrace, and opening the offending file at the offending line in your favorite editor (assuming your favorite editor supports remote open commands).

You can add filters that allow you to ignore some exceptions, and filters that allow you to scope the backtrace search. The backtrace scoping is useful for opening the last call in your application code when the exception occurs in a framework or lib.

If you are on MacOSX and have the growl gem installed, you will get a growl notification with the exception message when the file is opened.

Editors

Out if the box, the gem supports three editors (with the following open commands):

    :emacs => '/usr/bin/emacsclient -n +{line} {file}',
    :textmate => '/usr/local/bin/mate -a -d -l {line} {file}',
    :macvim => '/usr/local/bin/mvim +{line} {file}'

Note: if using emacs, you will need to be running emacsserver. To start the server: M-x server-start
or add (server-start) to your init.

Configuration

To configure, pass a block to the configure method:

    OpenException.configure do |oe|
      # open_with can be one of the built in editors (:emacs, :macvim, :textmate)
      # or a command to execute to open the file, where {file} and {line} will be replaced
      # with the file path and line number, respectively. See 'Editors' above for an example.
      # The default editor is :emacs.
 
      oe.open_with = :emacs
 
      # you can add exclusion filters to ignore exceptions. A filter can be an exception class to 
      # ignore, or a proc that is passed the exception, and should evaluate to true if the exception 
      # should be ignored. Be careful with using a class - it uses is_a?, so any subclasses of the
      # passed class will be ignored as well. The list of filters is [] by default.
 
      oe.exclusion_filters << SomeErrorClass
      oe.exclusion_filters << lambda { |exception| true if exception_should_be_excluded }
 
      # you can scope the search for the file:line to open with a filter as well. A filter can be a 
      # regular expression that is matched against the line, or a proc that is passed the line and 
      # should evaluate to true if the line should be used. The first line that any filter passes for 
      # will be the file:line that is opened. This is useful for opening the point in the stack just
      # before control passes out of your app code when the exception occurs in an external 
      # lib/framework. The list of filters is [] by default. 
 
      oe.backtrace_line_filters << %r{/app/root/(app|lib)} 
      oe.backtrace_line_filters << lambda { |backtrace_line| true if line_should_be_used }
 
    end

Rails Integration

The gem also alias chains in to rails’ ActionController#rescue_action_locally method to automatically open exceptions in development mode. The gem also adds the following filter to the :backtrace_line_filters to scope the opened files to the app:

    @%r{#{Rails.root}/(app|lib)}@

To replace or remove this filter, you will need to reset the :backtrace_line_filters in your configure block:

    OpenException.configure do |oe|
      oe.backtrace_line_filters = []
      oe.backtrace_line_filters << my_new_filter
    end

This has been tested with rails v2.3.5, but should work fine with 2.1 <= rails < 3. It may work with rails 3 as well, I just haven’t yet looked at rails 3.

Standalone/Other Frameworks

    # To manually open an exception, or wire it up in another framework, you call:
    OpenException.open(exception)
 
    # You can override the default (or configured) options by passing a hash as the second arg:
    OpenException.open(exception, {:open_with => :textmate, :backtrace_line_filters => [filter, another_filter])

The source is on github, and the gem is on rubygems.


Requires rinari

I’ve been an emacs user for 12+ years, and am ashamed to admit that I’ve never learned emacs lisp (yes, my last post was about emacs lisp code, but it was a copy and paste with a few changes, and I certainly didn’t understand what it was doing). Until now, that is. I started reading the emacs lisp intro, but only got about fifty pages in to it before I got the itch to write some code.

So here it is. Its a package that allows you to comment out a block of ruby code from a keybinding (I’m sure there is code out there to do this already, but it was a fun learning challenge).

The main function is comment-ruby, which I have bound to C-:. If there is a region active, it comments out the region. If that region is less than five lines, each line is commented with ‘# ‘, otherwise the entire region is wrapped in =begin...=end. If the region is not active, the current line is commented out with ‘# ‘.

After a region has been commented out, the point (cursor) is set to the line above or below the region, depending on whether the point was at the beginning or end of the region when called.

Here is the code – it probably isn’t idiomatic lisp. If you have any suggestions on improving the code or making it more idiomatic, please let me know!

This post covers how to combine the awesomeness of ack with rinari in emacs to run ack in the project root by default. (If you aren’t using ack, definitely check it out for searching your codebase. If you aren’t using emacs, this post isn’t going to convince you to switch).

I’ve been using Kim van Wyk’s ack.el for a few months now, but was annoyed that I had to tell it the directory where to run ack, when in most cases I wanted it to run in the root of my Rails app. So I copied the ack function from ack.el and made one that only asks for the search pattern, then runs in the root of the app (provided by rinari’s rinari-root function). I then bound that function to C-c f a.

Here is the code:

Note: you will need rinari and ack.el loaded, and ack will need to be in your path.

I’m in the process of upgrading a rails app from 2.1 to 2.3, and 2.3 wants me to refresh some of the gemspecs for my vendored gems. Unfortunately, when I run rake gems:refresh_specs I get the dreaded:

rake aborted!
can't activate , already activated json-1.1.9

I was able to refresh the spec in question outside of rake with (in the console):

>> Rails::GemDependency.from_directory_name('vendor/gems/gem_name-0.1.0', false).refresh

Hopefully that helps someone else out.

The Quest

Like most programmers, I type a lot – many hours a day, most days of the week. The keyboard is the primary conduit of my creative expression most of the time, whether I’m writing code or constructing elaborate stories to impress friends, clients, or co-workers (aka email/chat/this blog). For the last couple of years, I’ve been mildly obsessed with making that conduit more efficient. I’ve tried several different keyboards and entirely new keyboard layouts.

I stopped the keyboard search with the Kinesis Advantage – it works really well for me, and is the easiest keyboard for touch typing that I’ve ever used. But the keyboard layout search continued. The productivity hit during the learning period for Dvorak or Colemak was too great, and I quickly slid back to Qwerty.

I could type as fast as I wanted in Qwerty, so I tried to figure out what was really bugging me about my typing. I realized it was the shift key – I was frustrated with the high percentage of characters I typed that involved shift. I primarily code in Ruby, which uses ‘_’ much more often than ‘-’ (about 14 times more often), ‘:’ more than ‘;’ (about 78 times more often!), and ‘{}’ more than ‘[]‘ (or so I thought – more on that later).

I then decided to create a custom keyboard layout that would reduce the need for the shift key when coding. My goals were:

  • no remapping of the letter keys, since my muscle memory knows where they all are
  • remap commonly used symbols to be available without the shift key
  • be easy to learn, so no remapping characters to new keys

Using the Ukelele keyboard layout editing tool (for MacOS), I played around with some layout ideas before settling on the one I’ve been using since May 2009.

The Layout

Since I mostly code in Ruby, and mostly use symbols in code vs. email/chat/etc., I remapped the shifted symbols I used more often.
I ‘shift-swapped’ (meaning the symbol you get with or without the shift key depressed are reversed) the following character pairs:

  • { [
  • } ]
  • | \
  • ~ `
  • : ;
  • _ -

I assumed that I used most of the symbols on the top row number keys more than I used the numbers, so I shift-swapped the 1 – 0 number keys with the corresponding symbol. If caps-lock is on, number keys revert to normal, but all of the other symbol keys remain swapped (meaning when caps-lock is on, pressing the ’1′ key will give you a 1, but pressing the ‘[' key will give you a {). Since the Kinesis keyboard does not have a separate keypad, this makes entering number sequences easier.

The caps-lock key has been moved to the f1 key, and I use the original caps-lock as a control key (for Emacs). This mapping can't be done by Ukelele, since it cannot remap function or modifier keys, so I did this using the remapping functionality in the Kinesis keyboard itself.

Analysis

After six weeks or so of using the new layout, I decided to analyze a large ruby codebase to see what my shift pair ratios actually were (something I should have done before creating a new layout). Using this script, I got the following results:

Analyzed 457 files, 25060 lines
` ~     25     58  2.320
1 !   1161    713  0.614
2 @    564   2700  4.787
3 #    416   1914  4.601
4 $    264     55  0.208
5 %    359    303  0.844
6 ^    257     44  0.171
7 &    152    226  1.487
8 *    176    115  0.653
9 (    196   4479  22.852
0 )   1761   4485  2.547
- _   1559  21837  14.007
[ {   1385   1304  0.942
] }   1396   1306  0.936
\ |    144   1480  10.278
; :    108   8446  78.204
= +   5588    729  0.130
‘ "   5585   3909  0.700
, <   4737    791  0.167
. >  10257   2067  0.202
/ ?   1077   1054  0.979

Columns one and two are the shift pairs. Columns three and four are the occurrence counts for each character in the pair. The last column shows the ratio of the second character (normally shifted) to the first character (normally not shifted). So a higher number in that column indicates an advantage to swapping the shift pair.

I looked at the shift pairs I had swapped, along with the other symbol shift pairs that I did not swap (the last five lines above). There are some big wins here with my current remapping, along with some loses. The '[]'/'{}' swap was a small mistake - looks like I access elements of collections slightly more often than I define inline blocks or explicit hashes (which is kind of obvious in hindsight. In fact, on reflection I would think that collection access would happen considerably more often than inline block creation). And some of the number key remaps are big loses based on the ratios, but the lowest ratio pairs there have generally low volume. After this analysis, I didn't undo any of the remappings, though I should have reversed (and still should reverse) the bracket/brace swap.

Usage

The name of this layout is 'rubyist'. If you are interested in giving it a try, download the MacOS keylayout file here, and put it in ~/Library/Keyboard Layouts/.

I don't expect this layout to work well for everyone, or really anyone other than me. I do think all of us could benefit from evaluating the text we type the most, and seeing if some keyboard layout tweaks could make us more efficient. If you do want to give your own layout a try, check out these platform specific tools:

pomodoro_status

For the last few months, I’ve been playing with the pomodoro technique to manage my time and stay focused on the task at hand. It works best for me when I’m stressed and have an overwhelming workload. It helps me focus on the immediate task, and not get distracted too much by all of the other stuff I need to do.

One issue with managing the technique is keeping interruptions to a minimum. When I start a pomodoro, I’ll quit email, twitter, and chat. But we are a distributed team, and I work from home 95% of the time. I want to let the rest of the team know I’m around, but also let them know that I’m in a pomodoro, and to only interrupt in emergencies. Since we primarily use Campfire to communicate, I set up a ‘Status’ room there that allows us to post what we are up to/where we are at/etc. Its not only useful for pomodoro updates, but also ‘off to lunch’, ‘gone for the day’, etc. (And here is a third sentence that ends in etc.) But manually entering those status updates means they won’t happen. So I wrote a simple update script using the lovely tinder gem. It consists of two files – the script itself:

and the config file (~/.campfire_status):

But pomodoro status updates still require a manual step to run the script. Enter Pomodoro, a MacOS pomodoro client by Ugo Landini. His client allows integration with growl, twitter, and applescript. So I added the following applescript snippets to update the status for me:

A couple of gotchas I ran in to:
* the Pomodoro app does not allow copy & paste in the applescript text areas, making it a bit of a pain to enter
* the Pomodoro app also has a file selector next to each applescript text area, but I could not get it to recognize the saved applescripts
* the Campfire API seems to ignore requests from users that are currently logged in(?), so the status updates come from another account (in our case, we have a ‘service-bot’ account that posts messages from other services). That’s why there is a USER_NAME setting that is displayed with the message.

I just released a stupid simple plugin based on the idea behind Coda Hale’s rails_environments plugin.

This plugin adds the following functionality to the Rails module to help with determining the current enviroment:

  >> Rails.environment       # a convenience alias to Rails.env
  => "development"
  >> Rails.development?
  => true
  >> Rails.not_development?
  => false
  >> Rails.production?
  => false
  >> Rails.not_production?
  => true
  >> Rails.test?
  => false
  >> Rails.not_test?
  => true

Not only does it provide env? and not_env? methods for the standard environments, it also provides those methods for any environment you define in config/environments/ (in fact that is how it learns about all of the environments, including the standard three). So if you define new environments in config/environments/ they will be picked up automatically.

Install with: script/plugin install git://github.com/tobias/rails_habitat.git

It lives on github.

Edit: see David’s comment below for the built in way to do this (in Rails >= 2.2).

We use Campfire for internal communication, and I’ve lately been pushing notifications there for all to see (Zendesk ticket updates, git repo pushes, etc). We decided it would be useful for the support team to know when a deployment occurs. I googled a bit to see if anyone had shared a Capistrano recipe, and did not find one. So I’m sharing mine.

Using the tinder gem, its super easy:

Enjoy!