Module: Scrivener::Validations

Included in:
Scrivener
Defined in:
lib/scrivener/validations.rb

Overview

Provides a base implementation for extensible validation routines. Validations currently only provides the following assertions:

  • assert

  • assert_present

  • assert_format

  • assert_numeric

  • assert_url

  • assert_email

  • assert_member

  • assert_length

  • assert_decimal

  • assert_equal

The core tenets that Scrivener::Validations advocates can be summed up in a few bullet points:

  1. Validations are much simpler and better done using composition rather than macros.

  2. Error messages should be kept separate and possibly in the view or presenter layer.

  3. It should be easy to write your own validation routine.

Other validations are simply added on a per-model or per-project basis.

If you want other validations you may want to take a peek at Ohm::Contrib and all of the validation modules it provides.

Examples:


class Quote
  attr_accessor :title
  attr_accessor :price
  attr_accessor :date

  def validate
    assert_present :title
    assert_numeric :price
    assert_format  :date, /\A[\d]{4}-[\d]{1,2}-[\d]{1,2}\z
  end
end

s = Quote.new
s.valid?
# => false

s.errors
# => { :title => [:not_present],
       :price => [:not_numeric],
       :date  => [:format] }

See Also:

Instance Method Summary collapse

Instance Method Details

#errorsObject

Hash of errors for each attribute in this model.



88
89
90
# File 'lib/scrivener/validations.rb', line 88

def errors
  @errors ||= Hash.new { |hash, key| hash[key] = [] }
end

#valid?Boolean

Check if the current model state is valid. Each call to #valid? will reset the #errors array.

All validations should be declared in a ‘validate` method.

Examples:


class 
  attr_accessor :username
  attr_accessor :password

  def validate
    assert_present :user
    assert_present :password
  end
end

Returns:

  • (Boolean)


77
78
79
80
81
# File 'lib/scrivener/validations.rb', line 77

def valid?
  errors.clear
  validate
  errors.empty?
end

#validateObject

Base validate implementation. Override this method in subclasses.



84
85
# File 'lib/scrivener/validations.rb', line 84

def validate
end