Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Created April 22, 2025 13:48
Show Gist options
  • Save ericboehs/b2ab422bd873727ffe7a96660de4c450 to your computer and use it in GitHub Desktop.
Save ericboehs/b2ab422bd873727ffe7a96660de4c450 to your computer and use it in GitHub Desktop.
Git hook for Rails projects that ensures dependencies are up-to-date and reminds devs to run pending migrations after switching branches
#!/usr/bin/env bash
set -euo pipefail
# Exit during rebases, merges, or detached HEADs
if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ] || [ -f .git/MERGE_HEAD ] || ! git symbolic-ref -q HEAD >/dev/null; then
echo "🔁 Skipping post-checkout hook (rebase/merge or detached HEAD)"
exit 0
fi
previous_head=$(git rev-parse HEAD@{1})
new_head=$(git rev-parse HEAD)
# Check for Gemfile.lock changes
if git diff --name-only "$previous_head" "$new_head" | grep -q '^Gemfile.lock$'; then
echo "📦 Gemfile.lock changed. Running bundle install..."
if ! bundle install; then
echo "❌ bundle install failed!" >&2
exit 1
fi
fi
# Warn if new migrations were added
if git diff --name-only "$previous_head" "$new_head" | grep -q '^db/migrate/'; then
echo "🛠️ New migration(s) detected. Don't forget to run:"
echo " rails db:migrate"
fi
@ericboehs
Copy link
Author

💡 A post-checkout Git hook for Ruby on Rails projects

This hook ensures you’re running the right dependencies and don’t forget pending migrations after switching branches.

Features

  • ✅ Runs bundle install when Gemfile.lock changes
  • ✅ Warns you if new files are added to db/migrate
  • ✅ Skips during rebases, merges, or detached HEAD states

Installation

  1. Save the script as .git/hooks/post-checkout in your Rails project.

  2. Make it executable:

    chmod +x .git/hooks/post-checkout

Now every time you checkout a branch, this hook will help keep your environment in sync.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment