Sometimes, I get to work with code that has been worked over by multiple developers, each with different sets of styling standards. Often, the code uses hard tabs, or random, inconsistent indentation. This makes the code difficult to understand at a glance.
There are two great tools to help style your code in a consistent way. The first beautifies Ruby code, and works with Rails/Merb models and controllers. You can get it from here. However, since I prefer softabs of 2 spaces (like most of the Ruby world), I edited the script to use 2 spaces instead of the default 3.
After dropping it into your ~/bin folder, you invoke rbeautifer.rb like so:
~/bin/rbeautifier.rb app/model/something.rb
It will first backup the existing file to something.rb~ and then format something.rb with sane styling. To apply this to all of your models and controllers, invoke it thus:
find app/ -name “*rb” | xargs ~/bin/rbeautifier.rb
The second tool beautifies your HTML erb templates. Sure, I know there are a lot of people who say I should be using HAML, but if I wanted to use HAML, I would be using Python, not Ruby. htmlbeautifier will Beautify your HTML erb templates (.rhtml and .html.erb files). You can get the original here but I have found a bug in r17 that doesn’t deal with broken templates very well. I fixed this in my github version located here. Making this work with broken templates is important, since I use it as a tool to diagnose broken templates.
You have to download it and then run setup.rb (it is gemified). You can then invoke it thus:
htmlbeautify < app/views/layouts/application.html.erb > app/views/layouts/application.html.erb-
Then I check the app/views/layouts/application.html.erb- to make sure it is the way I want it, before moving it over on top of the old one. You can write a shell script that will go through and beautify all of the templates, but I have not had a need for that yet. If I do, I’ll post it here.
Sorry, comments are closed for this article.