Synopsis

Add a shell script to TextMate that moves you from a controller file to its corresponding view (.rhtml) file in one keypress.

UPDATE

See the syncPeople on Rails Bundle for even more features and a much simpler installation.

Navigation Blues

One of the most inconvenient things about the Rails directory structure is the relative distance between the controller and its corresponding view files. While it’s organizationally sound, it’s often a pain to go hunting for a view (especially in a complicated application that has modules and modules within modules).

I discovered a fantastic little key-combo within TextMate the other day that almost did what I wanted–if you hit command-option-down, you will be taken from the controller to the corresponding functional test (or from a model to the corresponding unit test). Try it out, it’s really cool.

The Shortcut

But what I wanted was ease of navigation from my controllers to my views and vice versa. From what I could tell, that’s not a built-in feature of the Rails or Ruby TextMate command bundles. So I wrote one and bound it to command-option-up. Read on to add the command yourself.

Installation

Put the rails-open-view-partner.rb file in to the following directory:

~/Library/Application Support/TextMate/ \
    Bundles/Rails.tmbundle/Support/bin

Next, in TextMate go to the Automation -> Run Command -> Edit Commands menu (ctrl-option-command-c). Navigate to the Rails commands and add a command by clicking the ” ” sign at the bottom of the window. Call this new command something like “Open Controller / View”. It should be next to the “Open Test Case” command which is the other command I mentioned above.

In the Command(s) window on the right, add this code:

rails-open-view-partner.rb "$TM_FILEPATH" &>/dev/null &

For “Input” choose “none”, and for “Output” choose “Discard”. For “Activation”, choose “Key Equivalent” and type a key combination in to the input box next to it (I chose command-option-up, since it matches the command-option-down quite nicely).

Finally, for Scope Selector, type “source.ruby.rails, text.html.ruby”. Whew. You’re done.

Note: As we’ve discovered in the comments, it’s important to make this file executable by adding the permission: “chmod u x rails-open-view-partner.rb”. Also remember that the scoping rules for this command apply to Rails mode not just Ruby mode.

Usage

Now that you’ve got that all set up, try it out. Go to a controller, and within that controller move your cursor inside of some action (e.g. between “def new” and “end”). Hit command-option-up and you’ll be taken to new.rhtml. From within new.rhtml, hit command-option-up again, and you’ll be taken right back to the controller.

Enjoy!

Update for RadRails Users

Justin Forder pointed out that the RadRails team is looking to do something similar. Kyle Shank has posted about this very same issue and it looks like they’re going to add a quick shortcut command too. Nice work, guys!