LoginSignup
10
6

More than 5 years have passed since last update.

YARD macro を使った Rails scope のドキュメントの書き方

Last updated at Posted at 2018-07-06

YARD を使って、rails の scope のドキュメントを書こうとした時に、色々試行錯誤したのでメモ。

macro を使わない方法

# @!group Scopes はお好みで。

一般的な DSL 的な書き方にドキュメントをつける時の書き方。

class Post < ApplicationRecord
  # @!group Scopes

  # @!method active
  #   @!scope class
  #   @return [ActiveRecord::Relation]
  scope :active, -> { where(status: 'active') }

  # @!method nonactive
  #   @!scope class
  #   @return [ActiveRecord::Relation]
  scope :nonactive, -> { where.not(status: 'active') }

  # @!method status(status)
  #   @!scope class
  #   @param [String] status
  #   @return [ActiveRecord::Relation]
  scope :status, ->(status) { where(status: status) }

  # @!endgroup
end

macro を使った方法

同じようなドキュメントを書きまくる時に省力化出来るマクロを使った場合。

一番最初にマクロを定義してあげれば、以降同じメソッドを使ったものは自動的にドキュメントを認識して書いてくれるし、必要に応じて @ タグを追加できる。

class Post < ApplicationRecord
  # @!group Scopes

  # @!macro [attach] scope
  #   @!method $1
  #   @!scope class
  #   @return [ActiveRecord::Relation]
  scope :active, -> { where(status: 'active') }

  scope :nonactive, -> { where.not(status: 'active') }

  # @overload status(status)
  #   @param [Symbol] status
  scope :status, ->(status) { where(status: status) }

  # @!endgroup
end

HTML

HTML の出力結果はどちらも同じで、下記のような形になる。

# @!group Scopes 宣言を入れておくと、 Class Method Summary ではなく、 Scopes にサマリーがまとまって表示される。

HTML

試行錯誤した点

  • @!macro の宣言をリポジトリ全体のどこか1箇所だけでできないか試したけどダメだった。わかる人いたら教えてください!
  • guard 使って実行すると微妙に挙動が変わるところがあってハマる
  • @!macro を使う場合 @!methodo ではメソッドの宣言を上書きできなくて、@overload 使うと出来ることに気がつくのに時間がかかった

参考

File: Tags Overview — Documentation for yard (0.9.12)

10
6
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
10
6