Module: StrokeDB::Validations

Defined in:
lib/strokedb/document/dsl/validations.rb

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

ERROR_MESSAGES =
{
  :should_be_present => '#{meta}\'s #{slotname} should be present on #{on}',
  :invalid_type      => '#{meta}\'s #{slotname} should be of type #{validation_type}',
  :already_exists    => 'A document with a #{slotname} of #{slotvalue} already exists',
  :not_included      => 'Value of #{slotname} is not included in the list',
  :not_excluded      => 'Value of #{slotname} is reserved',
  :invalid_format    => 'Value of #{slotname} should match #{slotvalue}',
  :not_confirmed     => '#{meta}\'s #{slotname} doesn\'t match confirmation',
  :not_accepted      => '#{slotname} must be accepted',
  :wrong_length      => '#{slotname} has the wrong length (should be %d characters)',
  :too_short         => '#{slotname} is too short (minimum is %d characters)',
  :too_long          => '#{slotname} is too long (maximum is %d characters)',
  :invalid           => '#{slotname} is invalid',
  :must_be_integer   => '#{slotname} must be integer',
  :not_a_number      => '#{slotname} is not a number',
}.freeze
NUMERICALITY_CHECKS =

Validates whether the value of the specified attribute is numeric by trying to convert it to a float with Kernel.Float (if only_integer is false) or applying it to the regular expression /\A[+\-]?\d+\Z/ (if only_integer is set to true).

Item = Meta.new do
  validates_numericality_of :price
end
  • message - A custom error message (default is: “is not a number”)

  • on Specifies when this validation is active (default is :save, other options :create, :update)

  • only_integer Specifies whether the value has to be an integer, e.g. an integral value (default is false)

  • allow_nil Skip validation if attribute is nil (default is false). Notice that for fixnum and float columns empty strings are converted to nil

  • greater_than Specifies the value must be greater than the supplied value

  • greater_than_or_equal_to Specifies the value must be greater than or equal the supplied value

  • equal_to Specifies the value must be equal to the supplied value

  • less_than Specifies the value must be less than the supplied value

  • less_than_or_equal_to Specifies the value must be less than or equal the supplied value

  • odd Specifies the value must be an odd number

  • even Specifies the value must be an even number

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

{ 'greater_than' => :>, 'greater_than_or_equal_to' => :>=,
'equal_to' => :==, 'less_than' => :<, 'less_than_or_equal_to' => :<=,
'odd' => :odd?, 'even' => :even? }.freeze
RANGE_OPTIONS =

Validates that the specified slot matches the length restrictions supplied. Only one option can be used at a time:

Person = Meta.new do
  validates_length_of :first_name, :maximum=>30
  validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
  validates_length_of :fax, :in => 7..32, :allow_nil => true
  validates_length_of :phone, :in => 7..32, :allow_blank => true
  validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
  validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
  validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
end

Configuration options:

  • minimum - The minimum size of the attribute

  • maximum - The maximum size of the attribute

  • is - The exact size of the attribute

  • within - A range specifying the minimum and maximum size of the attribute

  • in - A synonym(or alias) for :within

  • allow_nil - Attribute may be nil; skip validation.

  • allow_blank - Attribute may be blank; skip validation.

  • too_long - The error message if the attribute goes over the maximum (default is: “is too long (maximum is %d characters)”)

  • too_short - The error message if the attribute goes under the minimum (default is: “is too short (min is %d characters)”)

  • wrong_length - The error message if using the :is method and the attribute is the wrong size (default is: “is the wrong length (should be %d characters)”)

  • message - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

%w(is within in minimum maximum).freeze
RANGE_VALIDATIONS =
{
  'is'      => [ :==, ERROR_MESSAGES[:wrong_length] ],
  'minimum' => [ :>=, ERROR_MESSAGES[:too_short] ],
  'maximum' => [ :<=, ERROR_MESSAGES[:too_long] ]
}.freeze
NUMERICALITY_ERRORS =
{ 
  'greater_than'             => '#{slotname} must be greater than %d', 
  'greater_than_or_equal_to' => '#{slotname} must be greater than or equal to %d',
  'equal_to'                 => '#{slotname} must be equal to %d', 
  'less_than'                => '#{slotname} must be less than %d',
  'less_than_or_equal_to'    => '#{slotname} must be less than or equal to %d',
  'odd'                      => '#{slotname} must be odd',
  'even'                     => '#{slotname} must be even',
}.freeze

Instance Method Summary collapse

Instance Method Details

#validates_acceptance_of(slotname, opts = {}) ⇒ Object

Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:

Person = Meta.new do
  validates_acceptance_of :terms_of_service
  validates_acceptance_of :eula, :message => "must be abided"
end

The terms_of_service and eula slots are virtualized. This check is performed only if terms_of_service is not nil and by default on save.

Configuration options:

  • message - A custom error message (default is: “must be accepted”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • allow_nil - Skip validation if attribute is nil. (default is true)

  • accept - Specifies value that is considered accepted. The default value is a string “1”, which makes it easy to relate to an HTML checkbox. This should be set to ‘true’ if you are validating a database column, since the attribute is typecast from “1” to true before validation.

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



308
309
310
311
312
313
314
315
316
317
# File 'lib/strokedb/document/dsl/validations.rb', line 308

def validates_acceptance_of(slotname, opts = {})
  register_validation("acceptance_of", slotname, opts, :not_accepted) do |opts|
    allow_nil = opts['allow_nil'].nil? ? true : !!opts['allow_nil']
    accept = opts['accept'] || "1"

    { :allow_nil => allow_nil, :accept => accept }
  end

  virtualizes slotname.to_s
end

#validates_associated(slotname, opts = {}) ⇒ Object

Validates whether the associated object or objects are all valid themselves. Works with any kind of association.

Book = Meta.new do
  has_many :pages

  validates_associated :pages, :library
end

Warning: If, after the above definition, you then wrote:

Page = Meta.new do
  belongs_to :book

  validates_associated :book
end

…this would specify a circular dependency and cause infinite recursion.

NOTE: This validation will not fail if the association hasn’t been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of (and, possibly, validates_type_of).

Configuration options:

  • message - A custom error message (default is: “is invalid”)

  • on Specifies when this validation is active (default is :save, other options :create, :update)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



436
437
438
# File 'lib/strokedb/document/dsl/validations.rb', line 436

def validates_associated(slotname, opts = {})
  register_validation('associated', slotname, opts, :invalid)
end

#validates_confirmation_of(slotname, opts = {}) ⇒ Object

Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:

Model:
  Person = Meta.new do
    validates_confirmation_of :password
    validates_confirmation_of :email_address, :message => "should match confirmation"
  end

View:
  <%= password_field "person", "password" %>
  <%= password_field "person", "password_confirmation" %>

The added password_confirmation slot is virtual; it exists only as an in-memory slot for validating the password. To achieve this, the validation adds accessors to the model for the confirmation slot. NOTE: This check is performed only if password_confirmation is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute:

validates_presence_of :password_confirmation, :if => :password_changed?

Configuration options:

  • message - A custom error message (default is: “doesn’t match confirmation”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



278
279
280
281
282
# File 'lib/strokedb/document/dsl/validations.rb', line 278

def validates_confirmation_of(slotname, opts = {})
  register_validation("confirmation_of", slotname, opts, :not_confirmed)

  virtualizes(slotname.to_s + "_confirmation")
end

#validates_exclusion_of(slotname, opts = {}) ⇒ Object

Validates that the value of the specified slot is not in a particular enumerable object.

Person = Meta.new do
  validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
  validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
  validates_exclusion_of :format, :in => %w( mov avi ), :message => 'extension #{slotvalue} is not allowed'
end

Configuration options:

  • in - An enumerable object of items that the value shouldn’t be part of

  • message - Specifies a customer error message (default is: “is reserved”)

  • allow_nil - If set to true, skips this validation if the attribute is null (default is: false)

  • allow_blank - If set to true, skips this validation if the attribute is blank (default is: false)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/strokedb/document/dsl/validations.rb', line 153

def validates_exclusion_of(slotname, opts={})
  register_validation("exclusion_of", slotname, opts, :not_excluded) do |opts|
    raise ArgumentError, "validates_exclusion_of requires :in set" unless opts['in']
    raise ArgumentError, "object must respond to the method include?" unless opts['in'].respond_to? :include?
    
    { 
      :in => opts['in'],
      :allow_nil => !!opts['allow_nil'],
      :allow_blank => !!opts['allow_blank'] 
    }
  end
end

#validates_format_of(slotname, opts = {}) ⇒ Object

Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression provided.

Person = Meta.new do
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
end

Note: use A and Z to match the start and end of the string, ^ and $ match the start/end of a line.

A regular expression must be provided or else an exception will be raised.

Configuration options:

  • message - A custom error message (default is: “is invalid”)

  • with - The regular expression used to validate the format with (note: must be supplied!)

  • on Specifies when this validation is active (default is :save, other options :create, :update)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



238
239
240
241
242
243
244
245
# File 'lib/strokedb/document/dsl/validations.rb', line 238

def validates_format_of(slotname, opts={})
  register_validation("format_of", slotname, opts, :invalid_format) do |opts|
    unless regexp = opts['with'].is_a?(Regexp)
      raise ArgumentError, "validates_format_of requires :with => regexp"
    end
    { :with => opts['with'] }
  end
end

#validates_inclusion_of(slotname, opts = {}) ⇒ Object

Validates whether the value of the specified slot is available in a particular enumerable object.

Person = Meta.new do
  validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
  validates_inclusion_of :age, :in => 0..99
  validates_inclusion_of :format, :in => %w( jpg gif png ), :message => 'extension #{slotvalue} is not included in the list'
end

Configuration options:

  • in - An enumerable object of available items

  • message - Specifies a customer error message (default is: “is not included in the list”)

  • allow_nil - If set to true, skips this validation if the slot is null (default is: false)

  • allow_blank - If set to true, skips this validation if the slot is blank (default is: false)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/strokedb/document/dsl/validations.rb', line 121

def validates_inclusion_of(slotname, opts={})
  register_validation("inclusion_of", slotname, opts, :not_included) do |opts|
    raise ArgumentError, "validates_inclusion_of requires :in set" unless opts['in']
    raise ArgumentError, "object must respond to the method include?" unless opts['in'].respond_to? :include?
    
    { 
      :in => opts['in'],
      :allow_nil => !!opts['allow_nil'],
      :allow_blank => !!opts['allow_blank'] 
    }
  end
end

#validates_length_of(slotname, opts = {}) ⇒ Object Also known as: validates_size_of



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/strokedb/document/dsl/validations.rb', line 359

def validates_length_of(slotname, opts = {})
  register_validation("length_of", slotname, opts, nil) do |opts|
    range_options = opts.reject { |opt, val| !RANGE_OPTIONS.include? opt }

    case range_options.size
      when 0
        raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
      when 1
        # Valid number of options; do nothing.
      else
        raise ArgumentError, 'Too many range options specified. Choose only one.'
    end

    ropt = range_options.keys.first
    ropt_value = range_options[ropt]

    opthash = {
      :allow_nil => !!opts['allow_nil'],
      :allow_blank => !!opts['allow_blank'] 
    }

    case ropt
      when 'within', 'in'
        raise ArgumentError, ":#{ropt} must be a Range" unless ropt_value.is_a? Range

        opthash[:too_short] = (opts['too_short'] || ERROR_MESSAGES[:too_short]) % ropt_value.begin
        opthash[:too_long]  = (opts['too_long']  || ERROR_MESSAGES[:too_long])  % ropt_value.end
        opthash[:range] = ropt_value
      
      when 'is', 'minimum', 'maximum'
        raise ArgumentError, ":#{ropt} must be a nonnegative Integer" unless ropt_value.is_a?(Integer) and ropt_value >= 0

        # Declare different validations per option.
        opthash[:message]  = (opts['message'] || RANGE_VALIDATIONS[ropt][1]) % ropt_value
        opthash[:method]   = RANGE_VALIDATIONS[ropt][0]
        opthash[:argument] = ropt_value
    end

    opthash
  end
end

#validates_numericality_of(slotname, opts = {}) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/strokedb/document/dsl/validations.rb', line 196

def validates_numericality_of(slotname, opts={})
  register_validation("numericality_of", slotname, opts, nil) do |opts|
    numeric_checks = opts.reject { |key, val| !NUMERICALITY_CHECKS.include? key }

    %w(odd even).each do |o|
      raise ArgumentError, ":#{o} must be set to true if set at all" if opts.include?(o) && opts[o] != true
    end

    (numeric_checks.keys - %w(odd even)).each do |option|
      raise ArgumentError, "#{option} must be a number" unless opts[option].is_a? Numeric
    end
 
    {
      :only_integer => opts['only_integer'],
      :numeric_checks => numeric_checks,
      :allow_nil => !!opts['allow_nil']
    }
  end          
end

#validates_presence_of(slotname, opts = {}) ⇒ Object

Validates that the specified slot exists in the document. Happens by default on save. Example:

Person = Meta.new do
  validates_presence_of :first_name
end

The first_name slot must be in the document.

Configuration options:

  • message - A custom error message (default is: “should be present on …”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



39
40
41
# File 'lib/strokedb/document/dsl/validations.rb', line 39

def validates_presence_of(slotname, opts={})
  register_validation("presence_of", slotname, opts, :should_be_present)
end

#validates_type_of(slotname, opts = {}) ⇒ Object

Validates that the specified slot value has a specific type. Happens by default on save. Example:

Person = Meta.new do
  validates_type_of :first_name, :as => :string
end

The first_name value for each Person must be unique.

Configuration options:

  • message - A custom error message (default is: “document with value already exists”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • allow_nil - If set to true, skips this validation if the attribute is null (default is: false)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

Warning

When the slot doesn’t exist, validation gets skipped.



64
65
66
67
68
69
70
71
72
73
# File 'lib/strokedb/document/dsl/validations.rb', line 64

def validates_type_of(slotname, opts={})
  register_validation("type_of", slotname, opts, :invalid_type) do |opts|
    raise ArgumentError, "validates_type_of requires :as => type" unless type = opts['as']

    { 
      :validation_type => type.to_s.camelize,
      :allow_nil => !!opts['allow_nil'] 
    }
  end
end

#validates_uniqueness_of(slotname, opts = {}) ⇒ Object

Validates that the specified slot value is unique in the store

Person = Meta.new do
  validates_uniqueness_of :first_name
end

The first_name slot must be in the document.

Configuration options:

  • message - A custom error message (default is: “A document with a … of … already exists”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • case_sensitive - Looks for an exact match. Ignored by non-text columns (true by default). NOT YET IMPLEMENTED

  • allow_nil - If set to true, skips this validation if the attribute is null (default is: false)

  • allow_blank - If set to true, skips this validation if the attribute is blank (default is: false)

  • if - Specifies a method or slot name to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.

  • unless - Specifies a method or slot name to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => ‘signup_step_less_than_three’). The method result or slot should be equal to a true or false value.



95
96
97
98
99
# File 'lib/strokedb/document/dsl/validations.rb', line 95

def validates_uniqueness_of(slotname, opts={})
  register_validation("uniqueness_of", slotname, opts, :already_exists) do |opts|
    { :allow_nil => !!opts['allow_nil'], :allow_blank => !!opts['allow_blank'] }
  end
end