Introduction
We have shared with you how we can keep our applications healthy with the article keeping your Ruby on Rails Applications Healthy. It’s important to have Rubocop
, Brakeman
and other tools to keep our application in line with the standards. However, in our day-to-day workflow, we tend to continue with our Ruby on Rails development and get focused with deadlines and requirements. Sometimes, we aren’t able to apply these tools to our code. It’s great if we have been applying them, but we can never be sure, as at some moments these manage to slip-off. It would be great if there is a standardised way of running these tools.
Solution
Lo and behold, the overcommit
gem. This is a gem that runs our favourite tools before we commit and even push our changes. With this gem, we can remove running bundle exec rspec
and bundle exec brakeman
to our routine and let git intervene on it. What’s also good about this is that it runs the tools only on the files that were changed.
Installation
- Run
gem install overcommit
- Run
overcommit --install
- Create an
.overcommit.yml
file on the root.
Sample Config
# .overcommit.yml
PreCommit:
RuboCop:
enabled: true
command: ["bundle", "exec", "rubocop", "-A"]
on_warn: fail
problem_on_unmodified_line: ignore
Fasterer:
enabled: true
PrePush:
RSpec:
enabled: true
Brakeman:
enabled: true
As shown in the configuration, we are checking the code with Rubocop
and Fasterer
during PreCommit
. Rubocop
is ensured to only run on the code that has changed and ignore other code with the problem_on_unmodified_line: ignore
option. We also made sure that whenever there is a Rubocop
being violated, it stops the commit from pushing with the on_warn: fail
option. For PrePush
we run RSpec
and Brakeman
, so these are only being run before we get to push our changes to the remote server.
Let’s Try it Out
I’ve added code that doesn’t follow the Rails standards and committed it.
$ git add .
$ git commit -m 'Induce rubocop'
Running pre-commit hooks
Analyzing for potential speed improvements.................[Fasterer] OK
Analyze with RuboCop........................................[RuboCop] FAILED
Errors on modified lines:
/home/----/Programming/-----/app/components/automation/-----/form_component.rb:15:11: C: Naming/PredicateName: Rename `is_this_okay` to `this_okay?`.
✗ One or more pre-commit hooks failed
As shown, Rubocop
has failed and we need to change our code and commit again so that the violation would not occur.
Other Configurations
overcommit
has plenty of options on its github. You can check it out and make tons of configurations for your app!
Conclusion
We’ve shared a good tool to keep our ourselves going with our own workflow while ensuring that the necessary tools are running without constant effort. Hope this helps you out and allows you to continue with your work with less hassle.