Ruby on Rails git pre-commit hook

git provides a few hooks so you can control the workflow of your source code commits. These hooks are placed inside your .git/hooks directory, and a inside there are a few samples to look at.

For my Ruby on Rails applications, I use the git pre-commit hook, to ensure that my Ruby code syntax is correct, and that it passes all my RSpec tests.

In your application directory, create a file in the git directory: .git/hooks/pre-commit

#!/usr/bin/env ruby
# vim: set syntax=ruby

flag = false

Dir["{app,config,lib,runners}/**/*/*.rb"].each do |file|
  result = `ruby -c #{file}`
  if $? != 0
    puts result
    flag = true

Dir["public/javascripts/**/*.js"].each do |file|
  result = `grep -n console #{file}`

  if $? == 0
    puts file
    puts result
    flag = true

exit 1 if flag

exec "rake spec"

Don’t forget to make it executable:

chmod u+x .git/hooks/pre-commit

Now you are ready to go.