Railsで比較のバリデーションを1行で書くGemつくった (created_at <= deleted_at)


Overview

AとBのカラムがあった時に、
A > B
などを検証するカスタムバリデーションを動的に追加してくれます

そんなGemの紹介です。
active_comparison_validator
RubyGems

ActiveComparisonValidator

Dynamically add validation for compare the column and the other column.
This gem provides a macro for comparing the column and the other column of the record. Type of the comparable column is Date Time Numeric, and all that jazz.

意訳

こんなことができます。
入社日 < 退社日
予算上限 >= 購入済み金額
携帯番号 != 代表番号

などなど、いろいろ使えます

Usage

Shopモデル(店舗)が
open_at(開店) < close_at(閉店) となっていることを検証してみます

class Shop < ActiveRecord::Base
  include ActiveComparisonValidator
  comparison_validator 'open_at < close_at'
end

引数の文字列とオペレータの間に、スペースを空けます
comparison_validator 'open_at < close_at'

関連

validates_timeliness
Gemのメンテできる & 日時だけの比較なら、こちらでおっけー!