Active Model EachValidator
EachValidator
是會在選項雜湊中給定的屬性中進行反覆運算的驗證器,呼叫 validate_each
方法,傳入記錄、屬性及值。
所有 Active Model 驗證都是建立在這個驗證器之上。
方法
- C
- N
- V
屬性
[R] | attributes |
類別公開方法
new(options) 連結
傳回新的驗證器執行個體。所有選項都可透過 options
讀取器取得,但 :attributes
選項會被移除,並改由 attributes
讀取器取得。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 140 def initialize(options) @attributes = Array(options.delete(:attributes)) raise ArgumentError, ":attributes cannot be blank" if @attributes.empty? super check_validity! end
執行個體公開方法
check_validity!() 連結
由初始化函式呼叫的鉤子方法,允許驗證提供的引數是否有效。例如,當提供無效選項時,你可以引發 ArgumentError
。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 168 def check_validity! end
validate(record) 連結
對提供的記錄執行驗證。預設情況下,這會呼叫 validate_each
來判定有效性,因此子類別應覆寫 validate_each
以加入驗證邏輯。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 150 def validate(record) attributes.each do |attribute| value = record.read_attribute_for_validation(attribute) next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) value = prepare_value_for_validation(value, record, attribute) validate_each(record, attribute, value) end end
validate_each(record, attribute, value) 連結
在子類別中覆寫此方法以加入驗證邏輯,在必要時將錯誤加入記錄的 errors
陣列。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 161 def validate_each(record, attribute, value) raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method" end