Code Folding for Ruby

Does anyone use code folding when navigating large Ruby files?

I’ve watched some tutorials of how it can be used with other languages, but when I try the same with a Ruby file it seems to be have erratically, e.g. zc folds all the methods of the class instead of just the current one.

I have folding on by default, but frequently turn it off (often globally) shortly after launching vim. However, when I first start digging into a new codebase it’s nice to get an overview of what kinds of methods (and how many) are in a given file.

I use this plugin:

" Auto-fold files upon open. Disable session-wide with: <leader>nf
Bundle 'bruno-/vim-ruby-fold'

And have these additional settings in my .vimrc

"fold settings
" ------------
" toggle folding with za.
" fold everything with zM
" unfold everything with zR.
" zm and zr can be used too
" set foldmethod=syntax   "fold based on syntax (except for haml below)
" set foldnestmax=10      "deepest fold is 10 levels
" set nofoldenable        "dont fold by default
autocmd BufNewFile,BufRead *.haml setl foldmethod=indent nofoldenable
autocmd! FileType nofile setl foldmethod=indent nofoldenable

" Space to toggle folds.
nnoremap <Space> za
vnoremap <Space> za

" Toggles folds being enabled for this vim session
function! FoldToggle()
  if(&foldenable == 1)
    au WinEnter * set nofen
    au WinLeave * set nofen
    au BufEnter * set nofen
    au BufLeave * set nofen
    :set nofen
    au WinEnter * set fen
    au WinLeave * set fen
    au BufEnter * set fen
    au BufLeave * set fen
    :set fen

nnoremap <Leader>nf :call FoldToggle()<CR>

I re-installed that plug-in and copied your config but I’m still seeing the same issue.

Let’s say you have this Ruby file:

class Foo
  def a

  def b

  def c

If I move my cursor to the line containing def a and hit zc, I would expect only the first method to be folded, but instead all three methods are folded.

However, if I quit vim, re-open the file and immediately hit zR (open all foldings), then nothing happens visually but zc then begins to work as expected. It’s as if the folding state is somehow messed up initially and zR fixes it.

So I’m not sure if I’m misunderstanding how to use folding, or there is some problem with my setup, or a bug in the plug-in.

If you pasted all of my settings then you should be able to toggle a fold with the space bar. I don’t use zc myself. The spacebar uses za.

I have the same problem if I use za.

I found an open issue for this problem, but if it’s working for you, then I wonder what’s different about our setups that might affect this.

Oh, I just noticed it was actually you who opened that issue a year ago!