About the Ruby Beautifier
Ruby opens blocks with words and closes them with end, which makes indentation a counting problem. This beautifier adds a level when a line begins with def, class, module, begin, case or for, or when it begins with if, unless, while or until in statement position, and it subtracts one for every end on the line. That last detail is what keeps a guard clause such as return nil if list.empty? flat, since the conditional there is a modifier rather than a block opener.
Blocks passed with do |item| add a level when the do ends the line, and blocks passed with curly braces are counted as brackets, so a single line map { |x| x * 2 } nets to zero. Continuation keywords get their own treatment: else, elsif, when, in, rescue and ensure print one level out and then reopen the body beneath them, which produces the standard case and when ladder.
Comments are read before keywords are counted, so a sentence containing the word end in a # comment cannot shift the file. Sections between =begin and =end are copied out verbatim. String literals are scanned as units, and their contents, including interpolation, are never altered.
Line breaks are preserved, so this fixes indentation rather than restyling code. RuboCop and its autocorrect mode remain the right tool for a real Ruby codebase. Here the target is a snippet from a gist, an error report or a chat message that needs to be readable right now. Rails files with ERB in them should go through the ERB layer separately.
How to use
- Paste a
.rbfile or a snippet into the left pane, or press Sample to load a small invoice class. - Leave Indent at 2 spaces, the community standard, or change it if your project differs.
- Look for a section that keeps drifting right; that points at a block whose
endis missing. - Use Copy or Download to take the tidied file away.
Common questions
- Does it understand one line guard clauses?
- Yes. A trailing
iforunlessin the middle of a line is not treated as a block opener, so the following lines keep their level. - How are case and when statements laid out?
- The
whenbranches sit at the same level ascaseand their bodies one level deeper, which is the layout the Ruby style guide describes. - Will heredocs and percent literals survive?
- Quoted strings are copied out untouched. Percent literals such as
%w[a b]are counted as brackets, which balances within the line and therefore has no effect on depth. - Can it fix a file with a missing end?
- It will not add one. The indentation drifting to the right is your clue about where the block was left open.