Ivan Tkalin

I’m a software engineer. I solve problems.

Navigating your Rails project codebase with vim

When you work with source code, it is always nice to have the abilty to quickly jump to class/method definitions for either your own code or code from one of your ruby gems. This articles describes how to do this in vim with exuberant ctags, guard, and guard-ctags-bundler.

Tags

A tag is an identifier that appears in a “tags” file. It is a sort of label that can be jumped to. For example: In C programs each function name can be used as a tag. The “tags” file has to be generated by a program like ctags, before the tag commands can be used.

We’ll need this tags generating software installed on our machine:

$ sudo aptitude install exuberant-ctags

When we have ctags program installed, we can now generate tags for our project sources and use it in vim. But as soon as we also want to be able to navigate our gems sources, and we want our tags file to be updated automatically, we should do more.

Guard and guard-ctags-bundler

Guard is a command line tool to easily handle events on file system modifications.

and

Guard-CTags-Bundler generates ctags for your project and for gems in your bundle. For project tags file tags is generated, for gems tags file gems.tags is generated.

Installation

Append 2 gems to your Gemfile:

group :development do
  gem 'guard'
  gem 'guard-ctags-bundler'
end

Install them with bundler:

$ bundle

Generate Guardfile:

$ bundle exec guard init guard-ctags-bundler

Launch guard:

$ bundle exec guard

Note: guard should be running in background, it will monitor your filesystem for changes and will tell guard-ctags-bundler to re-generate your project tags or gems’ tags in case of any changes.

Vim

Vim works with tags generated by ctags program out of the box, but as soon as we have 2 tag files (one for project tags and one for gems tags), we should tell vim to use both. Add to your .vimrc:

set tags+=gems.tags

Usage

Ensure that guard is running:

$ bundle exec guard

Force regeneration of gems tags (needed only first time, when tags are not generated yet):

$ touch Gemfiles.lock

Force regeneration of projects tags (needed only first time, when tags are not generated yet):

$ touch app/controllers/application_controller.rb

Open Vim, move cursor to any class/method, press ctrl-] to jump to first matched tag, or g] to view the list of matched tags and select tag you want to jump to. That’s it.

Update: Check out my ctrlp-tjump extension to replace standard tjump/tselect behaviour with something similar to Sublime and RubyMine ‘Go to declaration’ window.