LoginSignup
13
15

More than 5 years have passed since last update.

[Rails5]annotateってなんぞ?

Last updated at Posted at 2019-01-10

はじめに

Railsの勉強としてgem周りを触ってみる企画です。
今回は・・・

annotate

を試してみようかと思います。

どういうgemなの?

簡単にいうと各スキーマの情報をファイルの先頭(あるいは末尾)に
コメント記載してくれるgemです。

例えばこのテーブル(モデル)のカラムって何があったっけ?とか
そういう情報を毎回都度DBにアクスセスしてshow columnsしたりとか
Rails consoleでモデル生成して確認したりとか・・・
そういう面倒な作業をなくしてくれる便利もの。
では早速いきましょう。

検証環境

以下の環境で実施しました。

[client]
・MacOS Mojave(10.14.2)
・Vagrant 2.2.2
・VBoxManage 6.0.0

[virtual]
・CentOS 7.6
・Rails 5.2.2
・ruby 2.3.1

ご参考までに。

annotate導入

1.gemのインストール

事前にRails勉強用に作成したプロジェクトで進めます。
各MVCは適当に掲示板アプリを想定してPostsコントローラーなどを生成済みです。
(index,show,editの空ページが見れる程度)

$ rails g model post
$ rails g controller posts index show edit

その前提のもと、Gemfileに以下を追記。

Gemfile
# annotate
gem 'annotate'

追記したらインストール。

$ bundle install

-----------
Fetching annotate 2.7.4
Installing annotate 2.7.4
-----------
→無事に完了。

2.annotateの設定をする

マイグレーションを実行した時に、
自動的にannotateを動かしたいので、以下のコマンドを実行。

$ rails g annotate:install
    create  lib/tasks/auto_annotate_models.rake

マイグレーション時に自動的にannotateしたくない場合は、
上記インストールコマンドは不要。
都度必要に応じてannotateする場合は、

$ bundle exec annotate

のコマンドを実行する。

3.annotateを使ってみる

すでに、PostモデルやUserモデルを生成しているので、
既存のファイルに対してannotateを実行してみましょう。
コマンドは上記と同じ。

$ bundle exec annotate
Annotated (6): app/models/post.rb, test/models/post_test.rb, test/fixtures/posts.yml,
app/models/user.rb, test/models/user_test.rb, test/fixtures/users.yml

6ファイルに適用されました。

4.動作確認

試しにPostモデルを見てみましょう。

post.rb
# == Schema Information
#
# Table name: posts
#
#  id         :bigint(8)        not null, primary key
#  name       :string(255)
#  content    :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Post < ApplicationRecord
end

おお、ちゃんとスキーマ情報が追加されてますね。
素晴らしい。

所感

大きい規模のプロジェクトになると、
必然的にテーブル数も多くなるので、「あのテーブルのカラムどうなってたっけ」
とかって結構あるあるですね。

テーブル定義書をわざわざ開くのも面倒なので、
annotateを入れてスキーマ情報を載せるようにしておけば、
すっかり構成を忘れちゃっても簡単に確認が出来て良い!

おわりに

何かお気づきの点がありましたら、
ご指摘やアドバイス等頂けると大変助かります!

13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15