Format Ruby Code in Vim

Format Ruby code in Vim

Vimcasts has a useful screencast on this subject that you may be interested in

gg=G

gg => go to start of file
= => apply autoformatting
G => ... to the end of file

Bad formatting ruby code in Vim

To get Ruby indenting working you need to provide indenting configuration. Vim itself is not able to indent Ruby code, you could set the indentexpr variable to some similar language (like basic), but you wont be happy with results. Check your smartindent and indentexpr variables:

:set si?
:set indentexpr?

In my case they are set:

nosmartindent
indentexpr=GetRubyIndent()

The best way to configure vim for ruby is to use vim-ruby plugin: https://github.com/vim-ruby/vim-ruby

How to Autoindent Ruby source code in Vim

vimfiles includes ruby code smart indention and a lot of other useful things

ruby code is automatically formatted like

class Foo
def bar
if xxx
blah
else
blahblah
end
barfoo
barfoo
end
end

How do I reformat ruby code from the command line?

This should be a task of your editor. In vim (configured for Ruby), just press gg=G xD

A Ruby script that does it is available at: http://www.arachnoid.com/ruby/rbeautify.rb.html

Ruby syntax checking in vim

awesome_person is right, ":w !ruby -c" will do. To make it more convenient, add this line in your ~/.vimrc:

autocmd FileType ruby map <F9> :w<CR>:!ruby -c %<CR>

Then the syntax gets checked on pressing F9 key.

How do I auto format Ruby or .erb files in VS Code?

You can set format associations in VSCode, so .erb files would be treated like .html.

Go to File->Preferences->Settings->Click ... in top right corner->Open settings.json

Then add this piece of code to your settings.json

"files.associations": {
"*.html.erb": "html"
}

This is how I solved this problem. It will remove some of the code highlights but will autoformat HTML templates like an HTML document.

Vim Ruby hash indentation

try http://github.com/vim-ruby/vim-ruby

seems to be a comprehensive ruby support for vim.

Ruby Source code Auto-Formatter

There is RuboCop:

gem install rubocop
rubocop -a

It will also fix all the common mistakes.



Related Topics



Leave a reply



Submit