Module: ActiveObject::Validations

Defined in:
lib/active_object/validations.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VALIDATIONS =
%w( validate validate_on_create validate_on_update )

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



189
190
191
192
193
194
195
196
197
198
# File 'lib/active_object/validations.rb', line 189

def self.included(base) # :nodoc:
  base.extend ClassMethods
  base.class_eval do
    alias_method_chain :save, :validation
    alias_method_chain :save!, :validation
  end

  base.send :include, ActiveSupport::Callbacks
  base.define_callbacks *VALIDATIONS
end

Instance Method Details

#errorsObject

Returns the Errors object that holds all information about attribute error messages.



670
671
672
# File 'lib/active_object/validations.rb', line 670

def errors
  @errors ||= Errors.new(self)
end

#save_with_validation(perform_validation = true) ⇒ Object

The validation process on save can be skipped by passing false. The regular Base#save method is replaced with this when the validations module is mixed in, which it is by default.



633
634
635
636
637
638
639
# File 'lib/active_object/validations.rb', line 633

def save_with_validation(perform_validation = true)
  if perform_validation && valid? || !perform_validation
    save_without_validation
  else
    false
  end
end

#save_with_validation!Object

Attempts to save the record just like Base#save but will raise a ObjectInvalid exception instead of returning false if the record is not valid.



643
644
645
646
647
648
649
# File 'lib/active_object/validations.rb', line 643

def save_with_validation!
  if valid?
    save_without_validation!
  else
    raise ObjectInvalid.new(self)
  end
end

#valid?Boolean

Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.

Returns:

  • (Boolean)


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/active_object/validations.rb', line 652

def valid?
  errors.clear

  run_callbacks(:validate)
  validate

  if new_record?
    run_callbacks(:validate_on_create)
    validate_on_create
  else
    run_callbacks(:validate_on_update)
    validate_on_update
  end

  errors.empty?
end