Module: Roda::Component::Form::Validations

Included in:
Roda::Component::Form
Defined in:
lib/roda/component/form/validations.rb

Overview

Provides a base implementation for extensible validation routines. Scrivener::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] }

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.client?Boolean



68
69
70
# File 'lib/roda/component/form/validations.rb', line 68

def self.client?
  RUBY_ENGINE == 'opal'
end

.server?(&block) ⇒ Boolean



63
64
65
# File 'lib/roda/component/form/validations.rb', line 63

def self.server? &block
  RUBY_ENGINE == 'ruby'
end

Instance Method Details

#client?Boolean Also known as: client



58
59
60
# File 'lib/roda/component/form/validations.rb', line 58

def client?
  RUBY_ENGINE == 'opal'
end

#errorsObject

Hash of errors for each attribute in this model.



101
102
103
# File 'lib/roda/component/form/validations.rb', line 101

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

#server?(&block) ⇒ Boolean Also known as: server



53
54
55
# File 'lib/roda/component/form/validations.rb', line 53

def server? &block
  RUBY_ENGINE == 'ruby'
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


90
91
92
93
94
# File 'lib/roda/component/form/validations.rb', line 90

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

#validateObject

Base validate implementation. Override this method in subclasses.



97
98
# File 'lib/roda/component/form/validations.rb', line 97

def validate
end