Maybe you remember Rubyfmt, a Ruby autoformatter that we shared with you in our blog. In the Ruby community the seek for the One True Formatter has been going on for quite a while and at this point, there are already several projects to choose from. Let’s explore them and try to find out what Ruby code formatter to choose?
The two general approaches you can employ to format code are:
- Build the code’s AST and regenerate the formatted code straight from its AST.
- Use a mapping between the AST and the source file to update selectively parts of the existing file.
Let’s consider all of them:
Pretty-printing is an important feature of every code formatting tool. it would pretty up multi-line composite literals like arrays, hashes and the like. Ruby built-in
ap libraries are good examples of pretty-printers.
Ripper has been part of MRI since version 1.9. Many people consider it the canonical Ruby parser. If you opt to use Ripper you can potentially have a formatting tool with 0 runtime dependencies. The other benefits of using it are Its speed, maintains by the Ruby Core Team, base on MRI’s own parser.
Parser is a pretty awesome project in many regards: It’s fast, very well documented. portable, its AST format is very simple and very easy to work with. Parser bundles a module that allows you to easily rewrite the underlying source files. And It’s written mostly in Ruby.
rubyfmt that we already mentioned is extremely simple – just a single Ruby script, there’s not even a gem.
RuboCop – the only tools in the bunch that’s not a dedicated formatter. It’s also the only tool which can give you reasonable feedback about problems with your layout without fixing them.
Keep hacking, everyone! May your Ruby code be always perfectly formatted. Read the original article with more info that will help you to make your conclusion.
And don’t miss our Monthly trending Ruby on Rails repositories!