DEV Community

lucasprag
lucasprag

Posted on • Originally published at grokblog.io

Little trick to use ctags to jump to definition even inside gems like Rails on vim

If you don't know what is ctags

Ctags is a programming tool that generates an index file of names found in source and header files of various programming languages. Depending on the language, functions, variables, class members, macros and so on may be indexed. -- Wikipedia

In the case of Ruby you can jump to a method definition, class, etc using ctags which doesn't work 100% of the time but it helps a lot.

vim

Vim has a native functionality where you can :tag MyClass and it opens your class based on the index created by ctags.

You can extend this functionality as much as you like

" open tag of the word under the cursor, requires to run "ctargs -R ." before
command! JumpToTag execute ':tag ' . expand("<cword>")

command! JumpToTagOnVsplit :vsplit
      \| execute ':tag ' . expand("<cword>")

command! JumpToTagOnSplit :split
      \| execute ':tag ' . expand("<cword>")

Enter fullscreen mode Exit fullscreen mode

but there is one limitation when using Rails and other gems; you can't jump inside them, like :tag ApplicationRecord.

the trick

You can run bundle install and set the path to install gems inside your project so when you run ctags -R . all the gems get indexed.

bundle install --path=vendor/bundle
Enter fullscreen mode Exit fullscreen mode

But remember to git ignore them

# ~/.gitignore_global
vendor/bundle

Enter fullscreen mode Exit fullscreen mode

gutentags

If you don't like run ctags -R . all the time, there is a plugin for vim that runs ctags in the background while you are coding. It's called vim-gutentags. All you need to do is install it.

That's it, I hope you enjoyed this little trick to make our lives a bit easier when coding Rails on vim. 👍

Top comments (0)