Started added a validation mixin
Usage: class Invoice < CouchRest::ExtendedDocument include CouchRest::Validation property :client_name property :employee_name property :location # Validation validates_present :client_name, :employee_name validates_present :location, :message => "Hey stupid!, you forgot the location" end
This commit is contained in:
parent
475e970c26
commit
dfdcd79a58
17 changed files with 1391 additions and 4 deletions
|
@ -0,0 +1,75 @@
|
|||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
class AbsentFieldValidator < GenericValidator
|
||||
|
||||
def initialize(field_name, options={})
|
||||
super
|
||||
@field_name, @options = field_name, options
|
||||
end
|
||||
|
||||
def call(target)
|
||||
value = target.send(field_name)
|
||||
return true if (value.nil? || (value.respond_to?(:empty?) && value.empty?))
|
||||
|
||||
error_message = @options[:message] || ValidationErrors.default_error_message(:absent, field_name)
|
||||
add_error(target, error_message, field_name)
|
||||
|
||||
return false
|
||||
end
|
||||
end # class AbsentFieldValidator
|
||||
|
||||
module ValidatesAbsent
|
||||
|
||||
##
|
||||
#
|
||||
# @example [Usage]
|
||||
# require 'dm-validations'
|
||||
#
|
||||
# class Page
|
||||
#
|
||||
# property :unwanted_attribute, String
|
||||
# property :another_unwanted, String
|
||||
# property :yet_again, String
|
||||
#
|
||||
# validates_absent :unwanted_attribute
|
||||
# validates_absent :another_unwanted, :yet_again
|
||||
#
|
||||
# # a call to valid? will return false unless
|
||||
# # all three attributes are blank
|
||||
# end
|
||||
#
|
||||
def validates_absent(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::AbsentFieldValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesAbsent
|
||||
end # module Validation
|
||||
end # module CouchRest
|
117
lib/couchrest/validation/validators/format_validator.rb
Normal file
117
lib/couchrest/validation/validators/format_validator.rb
Normal file
|
@ -0,0 +1,117 @@
|
|||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
require 'pathname'
|
||||
require Pathname(__FILE__).dirname.expand_path + 'formats/email'
|
||||
require Pathname(__FILE__).dirname.expand_path + 'formats/url'
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class FormatValidator < GenericValidator
|
||||
|
||||
FORMATS = {}
|
||||
include CouchRest::Validation::Format::Email
|
||||
include CouchRest::Validation::Format::Url
|
||||
|
||||
def initialize(field_name, options = {}, &b)
|
||||
super(field_name, options)
|
||||
@field_name, @options = field_name, options
|
||||
@options[:allow_nil] = false unless @options.has_key?(:allow_nil)
|
||||
end
|
||||
|
||||
def call(target)
|
||||
value = target.validation_property_value(field_name)
|
||||
return true if @options[:allow_nil] && value.nil?
|
||||
|
||||
validation = @options[:as] || @options[:with]
|
||||
|
||||
raise "No such predefined format '#{validation}'" if validation.is_a?(Symbol) && !FORMATS.has_key?(validation)
|
||||
validator = validation.is_a?(Symbol) ? FORMATS[validation][0] : validation
|
||||
|
||||
valid = case validator
|
||||
when Proc then validator.call(value)
|
||||
when Regexp then value =~ validator
|
||||
else
|
||||
raise UnknownValidationFormat, "Can't determine how to validate #{target.class}##{field_name} with #{validator.inspect}"
|
||||
end
|
||||
|
||||
return true if valid
|
||||
|
||||
error_message = @options[:message] || ValidationErrors.default_error_message(:invalid, field_name)
|
||||
|
||||
field = Extlib::Inflection.humanize(field_name)
|
||||
error_message = error_message.call(field, value) if error_message.respond_to?(:call)
|
||||
|
||||
add_error(target, error_message, field_name)
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
#class UnknownValidationFormat < StandardError; end
|
||||
|
||||
end # class FormatValidator
|
||||
|
||||
module ValidatesFormat
|
||||
|
||||
##
|
||||
# Validates that the attribute is in the specified format. You may use the
|
||||
# :as (or :with, it's an alias) option to specify the pre-defined format
|
||||
# that you want to validate against. You may also specify your own format
|
||||
# via a Proc or Regexp passed to the the :as or :with options.
|
||||
#
|
||||
# @option :allow_nil<Boolean> true/false (default is true)
|
||||
# @option :as<Format, Proc, Regexp> the pre-defined format, Proc or Regexp to validate against
|
||||
# @option :with<Format, Proc, Regexp> an alias for :as
|
||||
#
|
||||
# @details [Pre-defined Formats]
|
||||
# :email_address (format is specified in DataMapper::Validation::Format::Email)
|
||||
# :url (format is specified in DataMapper::Validation::Format::Url)
|
||||
#
|
||||
# @example [Usage]
|
||||
#
|
||||
# class Page
|
||||
#
|
||||
# property :email, String
|
||||
# property :zip_code, String
|
||||
#
|
||||
# validates_format :email, :as => :email_address
|
||||
# validates_format :zip_code, :with => /^\d{5}$/
|
||||
#
|
||||
# # a call to valid? will return false unless:
|
||||
# # email is formatted like an email address
|
||||
# # and
|
||||
# # zip_code is a string of 5 digits
|
||||
#
|
||||
def validates_format(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::FormatValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesFormat
|
||||
end # module Validation
|
||||
end # module CouchRest
|
66
lib/couchrest/validation/validators/formats/email.rb
Normal file
66
lib/couchrest/validation/validators/formats/email.rb
Normal file
|
@ -0,0 +1,66 @@
|
|||
# encoding: binary
|
||||
|
||||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
module Format
|
||||
module Email
|
||||
|
||||
def self.included(base)
|
||||
CouchRest::Validation::FormatValidator::FORMATS.merge!(
|
||||
:email_address => [ EmailAddress, lambda { |field, value| '%s is not a valid email address'.t(value) }]
|
||||
)
|
||||
end
|
||||
|
||||
# RFC2822 (No attribution reference available)
|
||||
EmailAddress = begin
|
||||
alpha = "a-zA-Z"
|
||||
digit = "0-9"
|
||||
atext = "[#{alpha}#{digit}\!\#\$\%\&\'\*+\/\=\?\^\_\`\{\|\}\~\-]"
|
||||
dot_atom_text = "#{atext}+([.]#{atext}*)*"
|
||||
dot_atom = "#{dot_atom_text}"
|
||||
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
|
||||
text = "[\\x01-\\x09\\x11\\x12\\x14-\\x7f]"
|
||||
quoted_pair = "(\\x5c#{text})"
|
||||
qcontent = "(?:#{qtext}|#{quoted_pair})"
|
||||
quoted_string = "[\"]#{qcontent}+[\"]"
|
||||
atom = "#{atext}+"
|
||||
word = "(?:#{atom}|#{quoted_string})"
|
||||
obs_local_part = "#{word}([.]#{word})*"
|
||||
local_part = "(?:#{dot_atom}|#{quoted_string}|#{obs_local_part})"
|
||||
no_ws_ctl = "\\x01-\\x08\\x11\\x12\\x14-\\x1f\\x7f"
|
||||
dtext = "[#{no_ws_ctl}\\x21-\\x5a\\x5e-\\x7e]"
|
||||
dcontent = "(?:#{dtext}|#{quoted_pair})"
|
||||
domain_literal = "\\[#{dcontent}+\\]"
|
||||
obs_domain = "#{atom}([.]#{atom})*"
|
||||
domain = "(?:#{dot_atom}|#{domain_literal}|#{obs_domain})"
|
||||
addr_spec = "#{local_part}\@#{domain}"
|
||||
pattern = /^#{addr_spec}$/
|
||||
end
|
||||
|
||||
end # module Email
|
||||
end # module Format
|
||||
end # module Validation
|
||||
end # module CouchRest
|
43
lib/couchrest/validation/validators/formats/url.rb
Normal file
43
lib/couchrest/validation/validators/formats/url.rb
Normal file
|
@ -0,0 +1,43 @@
|
|||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
module Format
|
||||
module Url
|
||||
|
||||
def self.included(base)
|
||||
CouchRest::Validation::FormatValidator::FORMATS.merge!(
|
||||
:url => [ Url, lambda { |field, value| '%s is not a valid URL'.t(value) }]
|
||||
)
|
||||
end
|
||||
|
||||
Url = begin
|
||||
# Regex from http://www.igvita.com/2006/09/07/validating-url-in-ruby-on-rails/
|
||||
/(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
|
||||
end
|
||||
|
||||
end # module Url
|
||||
end # module Format
|
||||
end # module Validation
|
||||
end # module CouchRest
|
120
lib/couchrest/validation/validators/generic_validator.rb
Normal file
120
lib/couchrest/validation/validators/generic_validator.rb
Normal file
|
@ -0,0 +1,120 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
|
||||
# All validators extend this base class. Validators must:
|
||||
#
|
||||
# * Implement the initialize method to capture its parameters, also calling
|
||||
# super to have this parent class capture the optional, general :if and
|
||||
# :unless parameters.
|
||||
# * Implement the call method, returning true or false. The call method
|
||||
# provides the validation logic.
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
class GenericValidator
|
||||
|
||||
attr_accessor :if_clause, :unless_clause
|
||||
attr_reader :field_name
|
||||
|
||||
# Construct a validator. Capture the :if and :unless clauses when present.
|
||||
#
|
||||
# @param field<String, Symbol> The property specified for validation
|
||||
#
|
||||
# @option :if<Symbol, Proc> The name of a method or a Proc to call to
|
||||
# determine if the validation should occur.
|
||||
# @option :unless<Symbol, Proc> The name of a method or a Proc to call to
|
||||
# determine if the validation should not occur
|
||||
# All additional key/value pairs are passed through to the validator
|
||||
# that is sub-classing this GenericValidator
|
||||
#
|
||||
def initialize(field, opts = {})
|
||||
@if_clause = opts.delete(:if)
|
||||
@unless_clause = opts.delete(:unless)
|
||||
end
|
||||
|
||||
# Add an error message to a target resource. If the error corresponds to a
|
||||
# specific field of the resource, add it to that field, otherwise add it
|
||||
# as a :general message.
|
||||
#
|
||||
# @param <Object> target the resource that has the error
|
||||
# @param <String> message the message to add
|
||||
# @param <Symbol> field_name the name of the field that caused the error
|
||||
#
|
||||
# TODO - should the field_name for a general message be :default???
|
||||
#
|
||||
def add_error(target, message, field_name = :general)
|
||||
target.errors.add(field_name, message)
|
||||
end
|
||||
|
||||
# Call the validator. "call" is used so the operation is BoundMethod and
|
||||
# Block compatible. This must be implemented in all concrete classes.
|
||||
#
|
||||
# @param <Object> target the resource that the validator must be called
|
||||
# against
|
||||
# @return <Boolean> true if valid, otherwise false
|
||||
def call(target)
|
||||
raise NotImplementedError, "CouchRest::Validation::GenericValidator::call must be overriden in a subclass"
|
||||
end
|
||||
|
||||
# Determines if this validator should be run against the
|
||||
# target by evaluating the :if and :unless clauses
|
||||
# optionally passed while specifying any validator.
|
||||
#
|
||||
# @param <Object> target the resource that we check against
|
||||
# @return <Boolean> true if should be run, otherwise false
|
||||
def execute?(target)
|
||||
if unless_clause = self.unless_clause
|
||||
if unless_clause.is_a?(Symbol)
|
||||
return false if target.send(unless_clause)
|
||||
elsif unless_clause.respond_to?(:call)
|
||||
return false if unless_clause.call(target)
|
||||
end
|
||||
end
|
||||
|
||||
if if_clause = self.if_clause
|
||||
if if_clause.is_a?(Symbol)
|
||||
return target.send(if_clause)
|
||||
elsif if_clause.respond_to?(:call)
|
||||
return if_clause.call(target)
|
||||
end
|
||||
end
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def ==(other)
|
||||
self.class == other.class &&
|
||||
self.field_name == other.field_name &&
|
||||
self.class == other.class &&
|
||||
self.if_clause == other.if_clause &&
|
||||
self.unless_clause == other.unless_clause &&
|
||||
self.instance_variable_get(:@options) == other.instance_variable_get(:@options)
|
||||
end
|
||||
|
||||
end # class GenericValidator
|
||||
end # module Validation
|
||||
end # module CouchRest
|
134
lib/couchrest/validation/validators/length_validator.rb
Normal file
134
lib/couchrest/validation/validators/length_validator.rb
Normal file
|
@ -0,0 +1,134 @@
|
|||
# Extracted from dm-validations 0.9.10
|
||||
#
|
||||
# Copyright (c) 2007 Guy van den Berg
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class LengthValidator < GenericValidator
|
||||
|
||||
def initialize(field_name, options)
|
||||
super
|
||||
@field_name = field_name
|
||||
@options = options
|
||||
|
||||
@min = options[:minimum] || options[:min]
|
||||
@max = options[:maximum] || options[:max]
|
||||
@equal = options[:is] || options[:equals]
|
||||
@range = options[:within] || options[:in]
|
||||
|
||||
@validation_method ||= :range if @range
|
||||
@validation_method ||= :min if @min && @max.nil?
|
||||
@validation_method ||= :max if @max && @min.nil?
|
||||
@validation_method ||= :equals unless @equal.nil?
|
||||
end
|
||||
|
||||
def call(target)
|
||||
field_value = target.validation_property_value(field_name)
|
||||
return true if @options[:allow_nil] && field_value.nil?
|
||||
|
||||
field_value = '' if field_value.nil?
|
||||
|
||||
# XXX: HACK seems hacky to do this on every validation, probably should
|
||||
# do this elsewhere?
|
||||
field = Extlib::Inflection.humanize(field_name)
|
||||
min = @range ? @range.min : @min
|
||||
max = @range ? @range.max : @max
|
||||
equal = @equal
|
||||
|
||||
case @validation_method
|
||||
when :range then
|
||||
unless valid = @range.include?(field_value.size)
|
||||
error_message = ValidationErrors.default_error_message(:length_between, field, min, max)
|
||||
end
|
||||
when :min then
|
||||
unless valid = field_value.size >= min
|
||||
error_message = ValidationErrors.default_error_message(:too_short, field, min)
|
||||
end
|
||||
when :max then
|
||||
unless valid = field_value.size <= max
|
||||
error_message = ValidationErrors.default_error_message(:too_long, field, max)
|
||||
end
|
||||
when :equals then
|
||||
unless valid = field_value.size == equal
|
||||
error_message = ValidationErrors.default_error_message(:wrong_length, field, equal)
|
||||
end
|
||||
end
|
||||
|
||||
error_message = @options[:message] || error_message
|
||||
|
||||
add_error(target, error_message, field_name) unless valid
|
||||
|
||||
return valid
|
||||
end
|
||||
|
||||
end # class LengthValidator
|
||||
|
||||
module ValidatesLength
|
||||
|
||||
# Validates that the length of the attribute is equal to, less than,
|
||||
# greater than or within a certain range (depending upon the options
|
||||
# you specify).
|
||||
#
|
||||
# @option :allow_nil<Boolean> true/false (default is true)
|
||||
# @option :minimum ensures that the attribute's length is greater than
|
||||
# or equal to the supplied value
|
||||
# @option :min alias for :minimum
|
||||
# @option :maximum ensures the attribute's length is less than or equal
|
||||
# to the supplied value
|
||||
# @option :max alias for :maximum
|
||||
# @option :equals ensures the attribute's length is equal to the
|
||||
# supplied value
|
||||
# @option :is alias for :equals
|
||||
# @option :in<Range> given a Range, ensures that the attributes length is
|
||||
# include?'ed in the Range
|
||||
# @option :within<Range> alias for :in
|
||||
#
|
||||
# @example [Usage]
|
||||
#
|
||||
# class Page
|
||||
#
|
||||
# property high, Integer
|
||||
# property low, Integer
|
||||
# property just_right, Integer
|
||||
#
|
||||
# validates_length :high, :min => 100000000000
|
||||
# validates_length :low, :equals => 0
|
||||
# validates_length :just_right, :within => 1..10
|
||||
#
|
||||
# # a call to valid? will return false unless:
|
||||
# # high is greater than or equal to 100000000000
|
||||
# # low is equal to 0
|
||||
# # just_right is between 1 and 10 (inclusive of both 1 and 10)
|
||||
#
|
||||
def validates_length(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::LengthValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesLength
|
||||
end # module Validation
|
||||
end # module CouchRest
|
66
lib/couchrest/validation/validators/method_validator.rb
Normal file
66
lib/couchrest/validation/validators/method_validator.rb
Normal file
|
@ -0,0 +1,66 @@
|
|||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class MethodValidator < GenericValidator
|
||||
|
||||
def initialize(field_name, options={})
|
||||
super
|
||||
@field_name, @options = field_name, options.clone
|
||||
@options[:method] = @field_name unless @options.has_key?(:method)
|
||||
end
|
||||
|
||||
def call(target)
|
||||
result, message = target.send(@options[:method])
|
||||
add_error(target, message, field_name) unless result
|
||||
result
|
||||
end
|
||||
|
||||
def ==(other)
|
||||
@options[:method] == other.instance_variable_get(:@options)[:method] && super
|
||||
end
|
||||
end # class MethodValidator
|
||||
|
||||
module ValidatesWithMethod
|
||||
|
||||
##
|
||||
# Validate using the given method. The method given needs to return:
|
||||
# [result::<Boolean>, Error Message::<String>]
|
||||
#
|
||||
# @example [Usage]
|
||||
#
|
||||
# class Page
|
||||
#
|
||||
# property :zip_code, String
|
||||
#
|
||||
# validates_with_method :in_the_right_location?
|
||||
#
|
||||
# def in_the_right_location?
|
||||
# if @zip_code == "94301"
|
||||
# return true
|
||||
# else
|
||||
# return [false, "You're in the wrong zip code"]
|
||||
# end
|
||||
# end
|
||||
#
|
||||
# # A call to valid? will return false and
|
||||
# # populate the object's errors with "You're in the
|
||||
# # wrong zip code" unless zip_code == "94301"
|
||||
#
|
||||
# # You can also specify field:
|
||||
#
|
||||
# validates_with_method :zip_code, :in_the_right_location?
|
||||
#
|
||||
# # it will add returned error message to :zip_code field
|
||||
#
|
||||
def validates_with_method(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::MethodValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesWithMethod
|
||||
end # module Validation
|
||||
end # module CouchRest
|
81
lib/couchrest/validation/validators/numeric_validator.rb
Normal file
81
lib/couchrest/validation/validators/numeric_validator.rb
Normal file
|
@ -0,0 +1,81 @@
|
|||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class NumericValidator < GenericValidator
|
||||
|
||||
def initialize(field_name, options={})
|
||||
super
|
||||
@field_name, @options = field_name, options
|
||||
@options[:integer_only] = false unless @options.has_key?(:integer_only)
|
||||
end
|
||||
|
||||
def call(target)
|
||||
value = target.send(field_name)
|
||||
return true if @options[:allow_nil] && value.nil?
|
||||
|
||||
value = value.kind_of?(BigDecimal) ? value.to_s('F') : value.to_s
|
||||
|
||||
error_message = @options[:message]
|
||||
precision = @options[:precision]
|
||||
scale = @options[:scale]
|
||||
|
||||
if @options[:integer_only]
|
||||
return true if value =~ /\A[+-]?\d+\z/
|
||||
error_message ||= ValidationErrors.default_error_message(:not_an_integer, field_name)
|
||||
else
|
||||
# FIXME: if precision and scale are not specified, can we assume that it is an integer?
|
||||
# probably not, as floating point numbers don't have hard
|
||||
# defined scale. the scale floats with the length of the
|
||||
# integral and precision. Ie. if precision = 10 and integral
|
||||
# portion of the number is 9834 (4 digits), the max scale will
|
||||
# be 6 (10 - 4). But if the integral length is 1, max scale
|
||||
# will be (10 - 1) = 9, so 1.234567890.
|
||||
if precision && scale
|
||||
#handles both Float when it has scale specified and BigDecimal
|
||||
if precision > scale && scale > 0
|
||||
return true if value =~ /\A[+-]?(?:\d{1,#{precision - scale}}|\d{0,#{precision - scale}}\.\d{1,#{scale}})\z/
|
||||
elsif precision > scale && scale == 0
|
||||
return true if value =~ /\A[+-]?(?:\d{1,#{precision}}(?:\.0)?)\z/
|
||||
elsif precision == scale
|
||||
return true if value =~ /\A[+-]?(?:0(?:\.\d{1,#{scale}})?)\z/
|
||||
else
|
||||
raise ArgumentError, "Invalid precision #{precision.inspect} and scale #{scale.inspect} for #{field_name} (value: #{value.inspect} #{value.class})"
|
||||
end
|
||||
elsif precision && scale.nil?
|
||||
# for floats, if scale is not set
|
||||
|
||||
#total number of digits is less or equal precision
|
||||
return true if value.gsub(/[^\d]/, '').length <= precision
|
||||
|
||||
#number of digits before decimal == precision, and the number is x.0. same as scale = 0
|
||||
return true if value =~ /\A[+-]?(?:\d{1,#{precision}}(?:\.0)?)\z/
|
||||
else
|
||||
return true if value =~ /\A[+-]?(?:\d+|\d*\.\d+)\z/
|
||||
end
|
||||
error_message ||= ValidationErrors.default_error_message(:not_a_number, field_name)
|
||||
end
|
||||
|
||||
add_error(target, error_message, field_name)
|
||||
|
||||
# TODO: check the gt, gte, lt, lte, and eq options
|
||||
|
||||
return false
|
||||
end
|
||||
end # class NumericValidator
|
||||
|
||||
module ValidatesIsNumber
|
||||
|
||||
# Validate whether a field is numeric
|
||||
#
|
||||
def validates_is_number(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::NumericValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesIsNumber
|
||||
end # module Validation
|
||||
end # module CouchRest
|
|
@ -0,0 +1,86 @@
|
|||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class RequiredFieldValidator < GenericValidator
|
||||
|
||||
def initialize(field_name, options={})
|
||||
super
|
||||
@field_name, @options = field_name, options
|
||||
end
|
||||
|
||||
def call(target)
|
||||
value = target.validation_property_value(field_name)
|
||||
property = target.validation_property(field_name)
|
||||
return true if present?(value, property)
|
||||
|
||||
error_message = @options[:message] || default_error(property)
|
||||
add_error(target, error_message, field_name)
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Boolean property types are considered present if non-nil.
|
||||
# Other property types are considered present if non-blank.
|
||||
# Non-properties are considered present if non-blank.
|
||||
def present?(value, property)
|
||||
boolean_type?(property) ? !value.nil? : !value.blank?
|
||||
end
|
||||
|
||||
def default_error(property)
|
||||
actual = boolean_type?(property) ? :nil : :blank
|
||||
ValidationErrors.default_error_message(actual, field_name)
|
||||
end
|
||||
|
||||
# Is +property+ a boolean property?
|
||||
#
|
||||
# Returns true for Boolean, ParanoidBoolean, TrueClass, etc. properties.
|
||||
# Returns false for other property types.
|
||||
# Returns false for non-properties.
|
||||
def boolean_type?(property)
|
||||
property ? property.primitive == TrueClass : false
|
||||
end
|
||||
|
||||
end # class RequiredFieldValidator
|
||||
|
||||
module ValidatesPresent
|
||||
|
||||
##
|
||||
# Validates that the specified attribute is present.
|
||||
#
|
||||
# For most property types "being present" is the same as being "not
|
||||
# blank" as determined by the attribute's #blank? method. However, in
|
||||
# the case of Boolean, "being present" means not nil; i.e. true or
|
||||
# false.
|
||||
#
|
||||
# @note
|
||||
# dm-core's support lib adds the blank? method to many classes,
|
||||
# @see lib/dm-core/support/blank.rb (dm-core) for more information.
|
||||
#
|
||||
# @example [Usage]
|
||||
#
|
||||
# class Page
|
||||
#
|
||||
# property :required_attribute, String
|
||||
# property :another_required, String
|
||||
# property :yet_again, String
|
||||
#
|
||||
# validates_present :required_attribute
|
||||
# validates_present :another_required, :yet_again
|
||||
#
|
||||
# # a call to valid? will return false unless
|
||||
# # all three attributes are !blank?
|
||||
# end
|
||||
def validates_present(*fields)
|
||||
opts = opts_from_validator_args(fields)
|
||||
add_validator_to_context(opts, fields, CouchRest::Validation::RequiredFieldValidator)
|
||||
end
|
||||
|
||||
end # module ValidatesPresent
|
||||
end # module Validation
|
||||
end # module CouchRest
|
Loading…
Add table
Add a link
Reference in a new issue