Rails Guideのサンプルコードの syntax error を修正してプルリクエストを送る
概要
Rails Guideの誤記を確認し、修正のプルリクエストを送るまで
経緯
Rails Guide の Active Record Validations を読んでいたところ
気になるサンプルコードが。
5.5 Combining Validation Conditions のサンプルコード
class Computer < ActiveRecord::Base
validates :mouse, presence: true,
if: ["market.retail?", :desktop?]
unless: Proc.new { |c| c.trackpad.present? }
end
if シンボルの行末にカンマがない。 syntax error かな?
validation の if/unless 列挙のパターンは使ったことがないので、
本当に syntax error か確認してみよう。
確認
ちょうど Rails4 の動作確認をしていたので Rails のプロジェクトは起動中。
上記のサンプルのケースにあうモデルを作ろう。
まずは generate と migration 。
$ rails g model computer mouse:string trackpad:boolean
$ rake db:migrate
モデルとテーブルができたので、各メソッドのValidation呼び出しが通るように適当にモデルを変更する。
class Computer < ActiveRecord::Base
validates :mouse, presence: true,
if: ["market.retail?", :desktop?]
unless: Proc.new { |c| c.trackpad.present? }
class Market
def retail?
true
end
end
def market
Market.new
end
def desktop?
true
end
end
そして、 rails console (pry) で動作確認
$ rails c
[1] pry(main)> c = Computer.new
SyntaxError: /home/vagrant/work_rails/blog/app/models/computer.rb:4: syntax error, unexpected ':'
unless: Proc.new { |c| c.trackpad.present? }
^
from /home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:443:in `load'
案の定エラー。
では、カンマを付けてみる。
$ rails c
[1] pry(main)> c = Computer.new
=> #<Computer id: nil, mouse: nil, market: nil, type: nil, trackpad: nil, created_at: nil, updated_at: nil>
問題なくインスタンスを作成できました。
やはり、 syntax error のようなのでプルリクエストを作成します。
前に一回 Rails Guilde のプルリクエストはマージしてもらっているので手順はわかってる。
上記の手順で1文字カンマを足すだけの簡単なお仕事です。
プルリクエスト作成完了
しばし待つ
しばし待つ・・・と思ったら 1分と立たずにマージされました
前回プルリクエストした時もあっという間にマージされたし、 Rails コミッター陣のマージは神速。
参照
- Rails Guide. Active Record Validations の 5.5 Combining Validation Conditions
- GitHubのRails Guide