Andy from Webcrunch

Subscribe for email updates:

Portrait of Andy Leverenz
Andy Leverenz

February 28, 2023

Last updated November 5, 2023

Rails Quick Tips - 05 - Annotate Gem

The annotate Ruby gem boosts developer quality of life and is one I use in every new Rails project.

The idea of the gem is to document a specific database table schema (and other optional logic) inside your model files using ruby comments. This then updates dynamically with each change to the database.

Annotate benefits you because you no longer need to find and hunt down how you've already architected the database in your db folder in a Ruby on Rails project.

Instead, you can refer to your models, make better decisions around what you see, and verify your models are in good shape.

Installation

Add the gem to your :development group inside your Rails application Gemfile.

# Gemfile

group :development do
  gem "annotate"
end

With the gem inside the group :development block, we can install it using bundler.

bundle install

Configuration

Installing the rake task from the gem is the easiest way to get started. You can accomplish this with a one-liner.

rails g annotate:install

This creates a task called auto_annotate_models.rake inside lib/tasks. When you run normal database migrations, your models should now show ruby comments matching the current schema you have in place for any corresponding table in your database.

This is useful for quick reference and saves time and energy verifying certain data and data types in your app as you can imagine, when a Ruby on Rails application scales, this will pay huge dividends.

If you want to run rails db:migrate as a one-off without running annotate, you can do so with a simple environment variable instead of editing the .rake file:

ANNOTATE_SKIP_ON_DB_MIGRATE=1 rake db:migrate

Options

The annotate gem ships with many options that can be run via the command line using the keyword annotate. Pass these options for different outcomes to suit your needs.

Link this article
Est. reading time: 2 minutes
Stats: 1,129 views

Categories

Collection

Part of the Rails Quick Tips collection

Products and courses