もふもふ技術部

IT技術系mofmofメディア

【Railsの便利gem】スキーマ情報をModelファイルにコメントで書き出してくれるannotate

annotateとは

アプリケーションの各モデルのスキーマ情報やルーティング情報を、ファイルの先頭にコメントで出力してくれるgemです。
これがあるとモデルにどんなカラムがあったかいちいちスキーマを確認したり、rake routesでルーティングを確認したりと言った手間が省けます。

バージョン

Ruby 2.6.5
Rails 6.0.3

導入手順

gemインストール

Gemfileに下記を追加してbundle install

group :development do
  gem 'annotate'
end

このgemは開発環境でしか使用しないのでgroup :developmentの中で指定すること。

annotateの設定

マイグレーション時に自動的にスキーマ情報をファイルに書き出したい場合は、下記のコマンドを実行してrakeファイルを作成しておきます。

$ rails g annotate:install

  create  lib/tasks/auto_annotate_models.rake

手動でスキーマ情報を書き出したい場合は、bundle exec annotate --modelsで逐次実行することも出来ます。

annotateの実行

スキーマ情報

それでは、実際にannotateを実行してみるとどうなるでしょうか。
下記のようなスキーマ情報を持つPostモデルがあったとします。

create_table "posts", force: :cascade do |t|
  t.string "title", default: "", null: false
  t.text "content", default: ""
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
end

ターミナルでbundle exec annotate --modelsを実行します。

$ bundle exec annotate --models
Annotated (3): app/models/post.rb, spec/factories/posts.rb, spec/models/post_spec.rb

これで3ファイルに対してannotateが実行されました。実際にファイルの中身を見てみます。

# app/models/post.rb

# == Schema Information
#
# Table name: posts
#
#  id         :bigint           not null, primary key
#  content    :text             default("")
#  title      :string           default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Post < ApplicationRecord
end
# spec/factories/posts.rb

# == Schema Information
#
# Table name: posts
#
#  id         :bigint           not null, primary key
#  content    :text             default("")
#  title      :string           default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

FactoryBot.define do
  factory :post do
  end
end
# spec/models/post_spec.rb

# == Schema Information
#
# Table name: posts
#
#  id         :bigint           not null, primary key
#  content    :text             default("")
#  title      :string           default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

require 'rails_helper'

RSpec.describe Post, type: :model do
end

ルーティング情報

bundle exec annotate --routesconfig/routes.rbに自動で出力してくれます。
これでルーティング確認のためにいつもやっていたrake routesも必要無くなりますね。

まとめ

いかがでしたでしょうか?今回はRailsでの開発のお助けgem、annotateをご紹介しました。
このgemを使うことで、特に複数人での開発の際に、カラム情報などをまとめる必要が無くなります。
便利なので是非使ってみてください。