LoginSignup
6

More than 5 years have passed since last update.

Rails でアノテーションを活用しよう!

Last updated at Posted at 2019-02-04

概要

アノテーションコメントを活用することで、確認すべき箇所や修正すべき箇所をコメントと併せてコード上に残し、後から確認することができます。

書き方

シャープ + 半角Space + アノテーションキーワード + コロン + 半角Space + コメントで記述します。

# KEYWORD: comment

複数行に渡る場合は

def bar
  # FIXME: This has crashed occasionally since v3.2.1. It may
  #   be related to the BarBazUtil upgrade.
  baz(:quux)
end

ソースコードと同じ行に描く場合は

def bar
  sleep 100 # OPTIMIZE
end

.html.erb に書く場合

viewファイル(.html.erb)に書く場合は、少し書き方が異なります。

<% #KEYWORD comment %>

アノテーションキーワード

Ruby Style Guideによると、以下のアノテーションキーワードが使用できます。

キーワード 内容
TODO あとで追加すべき機能
FIXME 修正が必要なコード
OPTIMIZE 遅い・非効率など最適化すべきコード
HACK リファクタリングした方が良さそうなコード
REVIEW レビューすべき箇所
OTHER 必要に応じてキーワードを追加。Readmeに記載すべし

参考までに Ruby Style Guide の原文も

  • Use TODO to note missing features or functionality that should be added at a later date.
  • Use FIXME to note broken code that needs to be fixed.
  • Use OPTIMIZE to note slow or inefficient code that may cause performance problems.
  • Use HACK to note code smells where questionable coding practices were used and should be refactored away.
  • Use REVIEW to note anything that should be looked at to confirm it is working as intended.
  • Use other custom annotation keywords if it feels appropriate, but be sure to document them in your project's README or similar.

アノテーションコメントを一覧表示する

ターミナルから以下のコマンドでプロジェクト内のアノテーションコメントを一覧表示できます。

$ rake notes

特定のキーワードのアノテーションを表示するには、以下のコマンドを実行します。

$ rake notes:custom ANNOTATION=TODO

カスタムキーワードも同様に、以下のコマンドで表示できます。

# CUSTOM: comment
$ rake notes:custom ANNOTATION=CUSTOM

参考

Ruby Style Guide
https://github.com/rubocop-hq/ruby-style-guide#comment-annotations

Ruby | アノテーションコメント(TODO、FIXME、OPTIMIZE、HACK、REVIEW)
https://qiita.com/tbpgr/items/1c046a877c6be4d89876

Rails | コード内のコメントを見つける方法 (TODO、FIXME、OPTIMIZE、HACK、REVIEW)
https://qiita.com/Yinaura/items/69584a09fee58efd163e

rake notesがviewファイル(.html.erb)で出てこない時の対処法
https://qiita.com/ihatov08/items/20f029950917b1d6905c

Rubyスタイルガイドを読む: コメント、アノテーション、マジックコメント
https://techracho.bpsinc.jp/hachi8833/2017_02_20/35769

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
6