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.

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] }

Instance Method Summary collapse

Instance Method Details

#errorsObject

Hash of errors for each attribute in this model.



81
82
83
# File 'lib/scrivener/validations.rb', line 81

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

#valid?(*args, **kargs) ⇒ 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 Login
  attr_accessor :username
  attr_accessor :password

  def validate
    assert_present :user
    assert_present :password
  end
end

Returns:

  • (Boolean)


70
71
72
73
74
# File 'lib/scrivener/validations.rb', line 70

def valid?(*args, **kargs)
  errors.clear
  validate(*args, **kargs)
  errors.empty?
end

#validate(*args, **kargs) ⇒ Object

Base validate implementation. Override this method in subclasses.



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

def validate(*args, **kargs)
end