Class: ActiveModel::Validations::TransitionValidator
- Inherits:
-
ActiveModel::Validator
- Object
- ActiveModel::Validator
- ActiveModel::Validations::TransitionValidator
- Defined in:
- lib/active_model/validations/transition_validator.rb
Instance Method Summary collapse
- #build_valid_transition_lookup(valid_transitions) ⇒ Object
-
#initialize(options) ⇒ TransitionValidator
constructor
A new instance of TransitionValidator.
- #validate(record) ⇒ Object
Constructor Details
#initialize(options) ⇒ TransitionValidator
Returns a new instance of TransitionValidator.
4 5 6 7 8 9 10 11 12 13 |
# File 'lib/active_model/validations/transition_validator.rb', line 4 def initialize() super @column = [:column].to_s valid_transitions = [:valid_transitions] @when_validations = [:when_validations] @inclusive = [:inclusive] @allowed_transitions = {} build_valid_transition_lookup(valid_transitions) end |
Instance Method Details
#build_valid_transition_lookup(valid_transitions) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/active_model/validations/transition_validator.rb', line 15 def build_valid_transition_lookup(valid_transitions) valid_transitions.each do |transition| [transition[:from]].flatten.each do |from| [transition[:to]].flatten.each do |to| requires_validation = transition[:requires].present? requires_when = transition[:when].present? @allowed_transitions[from] ||= [] next @allowed_transitions[from] << { to => { requires_validation: false } } unless requires_validation @allowed_transitions[from] << { to => { requires_validation: true, requires_when: requires_when, requires: transition[:requires].map do |key, value| { key => [value].flatten } end } } end end end end |
#validate(record) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/active_model/validations/transition_validator.rb', line 40 def validate(record) return true if @when_validations && when_condition_unmet?(record) return true unless record.persisted? changes = record.changes return true unless changes.has_key?(@column) column_change = changes[@column] original_value = column_change[0] new_value = column_change[1] valid_transitions = @allowed_transitions[original_value] if valid_transitions.nil? add_inclusion_errors(record, original_value, new_value) if @inclusive return true end transition = valid_transitions.find { |allowed_transition| allowed_transition[new_value] } return invalid_transition_error(record, original_value, new_value) unless transition requires_validation = transition[new_value][:requires_validation] return true unless requires_validation requires_validation_requirements = transition[new_value][:requires] validate_requires_field(requires_validation_requirements, original_value, new_value, record) end |