Add field details to model files - Annotate gem
Have you ever opened a Rails model and wondered about its corresponding fields? It is a question I had in 2012 and a question I have never had to wonder about ever since, thanks to the Annotate Models gem.
The annotate_models gem does one thing, and it does it well. It adds comments like these to models, fixtures, factories, tests and specs and more. In my opinion, it is one of the first gems that should get added to any Ruby on Rails project.
Example
Before:
class User < ApplicationRecord
acts_as_taggable_on :tags
end
require "test_helper"
class UserTest < ActiveSupport::TestCase
# ...
end
After:
class User < ApplicationRecord
acts_as_taggable_on :tags
end
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# email :string
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_users_on_email (email)
#
require "test_helper"
class UserTest < ActiveSupport::TestCase
# ...
end
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# email :string
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_users_on_email (email)
#
Installation and configuration
Install the gem annotate
under the development group. I would do bundle add annotate
, and then move the gem specification inside the development group.
# Gemfile
group :development do
gem 'annotate', '~> 3.2'
end
Then you need to generate the configuration rake file.
rails g annotate:install
I prefer to have the annotation at the bottom of the files. Here is my annotate
configuration. I usually search and replace before with after (in neoVIM and VIM :%s/before/after/g
).
# lib/tasks/auto_annotate_models.rake
Annotate.set_defaults(
# ...
'models' => 'true',
'position_in_routes' => 'after',
'position_in_class' => 'after',
'position_in_test' => 'after',
'position_in_fixture' => 'after',
'position_in_factory' => 'after',
'position_in_serializer' => 'after',
'show_foreign_keys' => 'true',
# ...
# ...
)
Once you run annotate
the library will annotate the models based on the configuration. Annote lib will automatically update annotated files when you run migrations.
jdeen@iMac:/Volumes/Dev/JDeen/Projects/Tutorials/elastic|master⚡
⇒ annotate
Annotated (9): app/models/fund.rb, test/models/fund_test.rb, test/fixtures/funds.yml, app/models/transaction.rb, test/models/transaction_test.rb, test/fixtures/transactions.yml, app/models/user.rb, test/models/user_test.rb, test/fixtures/users.yml
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.