This post will demonstrate how you can automate the annotations of your Rails models to help other devs get a better understanding of the model from the model file using the annotate gem.
We will use Rails to initialize the project demo-annotated-rails-models:
# Create a new rails project
$ rails new demo-rails-with-react-frontend
$ cd demo-rails-with-react-frontend
# Install required Gem
$ bundle add annotate --group="development"
# Create and migrate some models
$ bin/rails generate model User name:string email:string
$ bin/rails generate model Post title:string body:text
$ bin/rails generate model Comment body:text post:references
$ bin/rails db:migrate
In the above, we setup the annotate gem and then add some models to the project.
We don't actually need to start the server for this one. We can begin the annotation right now.
Annotating our models
If you check out app/models directory, you will see our model files for User, Post and Comment under user.rb, post.rb and comment.rb respectively.
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
# app/models/post.rb
class Post < ApplicationRecord
end
# app/models/user.rb
class User < ApplicationRecord
end
All the files at the moment are quite empty and don't actually tell us much about the models themselves. This is where the annotate gem comes in.
As the gem is already installed, we can run the following command to annotate our models:
If we now check out our files, you will see comment annotations at the top of the class.
# app/models/comment.rb
# == Schema Information
#
# Table name: comments
#
# id :integer not null, primary key
# body :text
# post_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Comment < ApplicationRecord
belongs_to :post
end
# app/models/post.rb
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# title :string
# body :text
# created_at :datetime not null
# updated_at :datetime not null
#
class Post < ApplicationRecord
end
# app/models/user.rb
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ApplicationRecord
end
As you can see, we now have more useful information added to our model files.
There is also the added bonus that the doc block itself can help fill out the quick preview information in your IDE, for example now in my VSCode:
My VSCode hover preview for the Comment model
Summary
Today's post demonstrated how to annotate your Rails models with the help of the annotate gem.
This is a nice little Developer Experience improvement that can also help onboard other engineers.