Yesterday I had to refactor a very large ruby class. It had a lot of methods and, to make it cleaner, I decided to sort methods alphabetically.
Is there a way to do this in vim? Of course there is, and it’s quite tricky - so let’s see how we can do it.
The basic idea is taken from this post on wincent.com, I just adapted it for ruby. All credits to this guy for his work :)
We’ll use the same approach of the original post: first we’ll collapse each ruby method on a single line, using a defined pattern to replace line terminators. We’ll proceed sorting the one-lined methods, and finally we’ll expand them back to multi-line.
These are the three commands, we’ll explain them in detail later:
:'<,'>g/\vdef\ /,/\v^\s*end$/ s/$\n/@@@ :'<,'>sort :'<,'>s/@@@/\r/g
Let’s do it step by step.