A Sane way of Slowly Adopting Code Conventions

1 minute read

Legacy ruby projects are often littered with code that just doesn’t follow any kind of code convention. Each developer that had a hand in a certain codebase can quickly give up an just go on with their own style. Even I am guilty of not spending time to follow any sort of coding convention even though I know that we should for consistency, & readability.

In my opinion, just like refactoring, in order to reduce the scope of things that I need to change, aim to correct coding convention violations while working on features. In particular, only change the files that you touched a.k.a The Boy Scout Rule.

I usually follow bbatsov’s Ruby Style Guide and conveniently, Rubocop enforces this by default. So, if you’re following any sort of git feature branching model, you can automatically enforce (most of) the style guide changes by checking out to the feature branch and use this script:

git diff master --name-status | awk '{print $2}' | grep ".rb" | xargs rubocop --auto-correct

That roughly transates to: get all changed ruby files (.rb) in the current feature branch and run each file through rubocop, autocorrecting (modifying) the files if possible.

I recommend saving the changes in a separate commit for easier code reviews.

You can also configure Rubocop to follow your own coding style guidelines.