How does one navigate Ruby methods in VIM?

Viewed 18932

I'm learning VIM for Rails development and would like to easily navigate methods in a file. So far I see several options:

  • Find 'def' by using

    /def<space>
    
  • Create a macro that corresponds to a key using q and record
  • use VIM marks? (not even sure what they do, they just sound promising

Anyone have any better ideas?

8 Answers

I wrote a small shell script using ag (The Silver Searcher). Define the following functions in your .vimrc

This method will expand the word under the cursor.

function! SearchForDeclarationCursor()
  let searchTerm = expand("<cword>")
  call SearchForDeclaration(searchTerm)
endfunction

Then declare the SearchForDeclaration method

function! SearchForDeclaration(term)
  let definition = 'def ' . a:term
  cexpr system('ag -w ' . shellescape(definition))
endfunction

Note that we are explicitly searching for def keyword. (You can use your language method signature syntax)

We then map the above function to a Leader command.

map <Leader>cd :call SearchForDeclarationCursor()<CR>

Now if you place your cursor anywhere on a method that is defined "in your project", and press <Leader>cd, it will navigate you to where the method is defined.

Note that a method can be defined in multiple classes. You can cycle using <Leader>n for next or <Leader>p for prev.

If you want a more detailed explanation for the above, I've written a blog post here: http://pradyumna.io/2017/12/17/search-ruby-method-declarations-in-vim.html

Hope this helps!

Related