[Ruby on Rails 3, Ruby on Rails 4] gems: annotate

モデルファイルにデータモデルを含んだコメントが追加されます。

[markdown]

## Gemfile

“`
group :development do
gem ‘annotate’
end
“`

## 使い方

データモデルが変わるたびにannotateを実行する。

“`
% bundle exec annotate
Annotated (1): User
“`

### app/models/user.rb

“`
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base attr_accessible :email, :name end ``` ### spec/models/user_spec.rb spec/models/user_spec.rb にも追記されていました。 ## Guard で自動化する あるかなとおもったらありました。 > * [guard/guard-annotate · GitHub](https://github.com/guard/guard-annotate)

“`
group :development do
gem ‘annotate’
gem ‘guard-annotate’
end
“`

“`
% bundle exec guard init annotate
15:27:43 – INFO – annotate guard added to Guardfile, feel free to edit it
“`

### Guardfile

以下が追記されました。

“`
guard ‘annotate’, :tests => true, :show_migration => true do
watch( ‘db/schema.rb’ )
# Uncomment the following line if you also want to run annotate anytime
# a model file changes
#watch( ‘app/models/**/*.rb’ )
# Uncomment the following line if you are running routes annotation
# with the “:routes => true” option
#watch( ‘config/routes.rb’ )
end
“`

`:tests => true, :show_migration => true do` オプションを2つ追加してみます。

## 確認する

Guardを再起動します。
モデルにカラムを追加し変更を加えてみる。

“`
% bundle exec rails g migration add_adm_to_users adm:boolean
invoke active_record
create db/migrate/20131021071436_add_adm_to_users.rb
% bundle exec rake db:migrate
== AddAdmToUsers: migrating ==================================================
— add_column(:users, :adm, :boolean)
-> 0.0014s
== AddAdmToUsers: migrated (0.0021s) =========================================
“`

Guard の結果表示。

“`
17:22:31 – INFO – Running annotate
Annotated (1): User
17:22:36 – INFO – Running: spec/models/user_spec.rb
Running tests with args [“–drb”, “-f”, “progress”, “-r”, “/Users/****/projects/sample_app/vendor/bundle/ruby/2.0.0/gems/guard-rspec-2.5.4/lib/guard/rspec/formatter.rb”, “-f”, “Guard::RSpec::Formatter”, “–failure-exit-code”, “2”, “spec/models/user_spec.rb”]…
No examples found.
Finished in 0.00507 seconds
0 examples, 0 failures
Randomized with seed 21646
Done.
“`

### app/models/user.rb, spec/models/user_spec.rb

“`
# == Schema Information
# Schema version: 20131021071436
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# adm :boolean
#
“`

`rake db:rollback` にも対応してくれました。

[/markdown]