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
|
@ -1,4 +1,5 @@
|
|||
require File.join(File.dirname(__FILE__), 'properties')
|
||||
require File.join(File.dirname(__FILE__), 'document_queries')
|
||||
require File.join(File.dirname(__FILE__), 'views')
|
||||
require File.join(File.dirname(__FILE__), 'design_doc')
|
||||
require File.join(File.dirname(__FILE__), 'design_doc')
|
||||
require File.join(File.dirname(__FILE__), 'validation')
|
203
lib/couchrest/mixins/validation.rb
Normal file
203
lib/couchrest/mixins/validation.rb
Normal file
|
@ -0,0 +1,203 @@
|
|||
# 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 'rubygems'
|
||||
require 'pathname'
|
||||
|
||||
class Object
|
||||
def validatable?
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
dir = File.join(Pathname(__FILE__).dirname.expand_path, '..', 'validation')
|
||||
|
||||
require File.join(dir, 'validation_errors')
|
||||
require File.join(dir, 'contextual_validators')
|
||||
|
||||
require File.join(dir, 'validators', 'generic_validator')
|
||||
require File.join(dir, 'validators', 'required_field_validator')
|
||||
require File.join(dir, 'validators', 'absent_field_validator')
|
||||
require File.join(dir, 'validators', 'format_validator')
|
||||
require File.join(dir, 'validators', 'length_validator')
|
||||
require File.join(dir, 'validators', 'numeric_validator')
|
||||
require File.join(dir, 'validators', 'method_validator')
|
||||
|
||||
module CouchRest
|
||||
module Validation
|
||||
|
||||
def self.included(base)
|
||||
base.extend(ClassMethods)
|
||||
end
|
||||
|
||||
# Return the ValidationErrors
|
||||
#
|
||||
def errors
|
||||
@errors ||= ValidationErrors.new
|
||||
end
|
||||
|
||||
# Mark this resource as validatable. When we validate associations of a
|
||||
# resource we can check if they respond to validatable? before trying to
|
||||
# recursivly validate them
|
||||
#
|
||||
def validatable?
|
||||
true
|
||||
end
|
||||
|
||||
# Alias for valid?(:default)
|
||||
#
|
||||
def valid_for_default?
|
||||
valid?(:default)
|
||||
end
|
||||
|
||||
# Check if a resource is valid in a given context
|
||||
#
|
||||
def valid?(context = :default)
|
||||
self.class.validators.execute(context, self)
|
||||
end
|
||||
|
||||
# Begin a recursive walk of the model checking validity
|
||||
#
|
||||
def all_valid?(context = :default)
|
||||
recursive_valid?(self, context, true)
|
||||
end
|
||||
|
||||
# Do recursive validity checking
|
||||
#
|
||||
def recursive_valid?(target, context, state)
|
||||
valid = state
|
||||
target.instance_variables.each do |ivar|
|
||||
ivar_value = target.instance_variable_get(ivar)
|
||||
if ivar_value.validatable?
|
||||
valid = valid && recursive_valid?(ivar_value, context, valid)
|
||||
elsif ivar_value.respond_to?(:each)
|
||||
ivar_value.each do |item|
|
||||
if item.validatable?
|
||||
valid = valid && recursive_valid?(item, context, valid)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return valid && target.valid?
|
||||
end
|
||||
|
||||
|
||||
def validation_property_value(name)
|
||||
self.respond_to?(name, true) ? self.send(name) : nil
|
||||
end
|
||||
|
||||
# Get the corresponding Resource property, if it exists.
|
||||
#
|
||||
# Note: CouchRest validations can be used on non-CouchRest resources.
|
||||
# In such cases, the return value will be nil.
|
||||
def validation_property(field_name)
|
||||
properties.find{|p| p.name == field_name}
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
include CouchRest::Validation::ValidatesPresent
|
||||
include CouchRest::Validation::ValidatesAbsent
|
||||
# include CouchRest::Validation::ValidatesIsConfirmed
|
||||
# include CouchRest::Validation::ValidatesIsPrimitive
|
||||
# include CouchRest::Validation::ValidatesIsAccepted
|
||||
include CouchRest::Validation::ValidatesFormat
|
||||
include CouchRest::Validation::ValidatesLength
|
||||
# include CouchRest::Validation::ValidatesWithin
|
||||
include CouchRest::Validation::ValidatesIsNumber
|
||||
include CouchRest::Validation::ValidatesWithMethod
|
||||
# include CouchRest::Validation::ValidatesWithBlock
|
||||
# include CouchRest::Validation::ValidatesIsUnique
|
||||
# include CouchRest::Validation::AutoValidate
|
||||
|
||||
# Return the set of contextual validators or create a new one
|
||||
#
|
||||
def validators
|
||||
@validations ||= ContextualValidators.new
|
||||
end
|
||||
|
||||
# Clean up the argument list and return a opts hash, including the
|
||||
# merging of any default opts. Set the context to default if none is
|
||||
# provided. Also allow :context to be aliased to :on, :when & group
|
||||
#
|
||||
def opts_from_validator_args(args, defaults = nil)
|
||||
opts = args.last.kind_of?(Hash) ? args.pop : {}
|
||||
context = :default
|
||||
context = opts[:context] if opts.has_key?(:context)
|
||||
context = opts.delete(:on) if opts.has_key?(:on)
|
||||
context = opts.delete(:when) if opts.has_key?(:when)
|
||||
context = opts.delete(:group) if opts.has_key?(:group)
|
||||
opts[:context] = context
|
||||
opts.mergs!(defaults) unless defaults.nil?
|
||||
opts
|
||||
end
|
||||
|
||||
# Given a new context create an instance method of
|
||||
# valid_for_<context>? which simply calls valid?(context)
|
||||
# if it does not already exist
|
||||
#
|
||||
def create_context_instance_methods(context)
|
||||
name = "valid_for_#{context.to_s}?" # valid_for_signup?
|
||||
if !self.instance_methods.include?(name)
|
||||
class_eval <<-EOS, __FILE__, __LINE__
|
||||
def #{name} # def valid_for_signup?
|
||||
valid?('#{context.to_s}'.to_sym) # valid?('signup'.to_sym)
|
||||
end # end
|
||||
EOS
|
||||
end
|
||||
|
||||
all = "all_valid_for_#{context.to_s}?" # all_valid_for_signup?
|
||||
if !self.instance_methods.include?(all)
|
||||
class_eval <<-EOS, __FILE__, __LINE__
|
||||
def #{all} # def all_valid_for_signup?
|
||||
all_valid?('#{context.to_s}'.to_sym) # all_valid?('signup'.to_sym)
|
||||
end # end
|
||||
EOS
|
||||
end
|
||||
end
|
||||
|
||||
# Create a new validator of the given klazz and push it onto the
|
||||
# requested context for each of the attributes in the fields list
|
||||
#
|
||||
def add_validator_to_context(opts, fields, klazz)
|
||||
fields.each do |field|
|
||||
validator = klazz.new(field, opts)
|
||||
if opts[:context].is_a?(Symbol)
|
||||
unless validators.context(opts[:context]).include?(validator)
|
||||
validators.context(opts[:context]) << validator
|
||||
create_context_instance_methods(opts[:context])
|
||||
end
|
||||
elsif opts[:context].is_a?(Array)
|
||||
opts[:context].each do |c|
|
||||
unless validators.context(c).include?(validator)
|
||||
validators.context(c) << validator
|
||||
create_context_instance_methods(c)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end # module ClassMethods
|
||||
end # module Validation
|
||||
|
||||
end # module CouchRest
|
169
lib/couchrest/mixins/views.rb
Normal file
169
lib/couchrest/mixins/views.rb
Normal file
|
@ -0,0 +1,169 @@
|
|||
module CouchRest
|
||||
module Mixins
|
||||
module Views
|
||||
|
||||
def self.included(base)
|
||||
base.extend(ClassMethods)
|
||||
# extlib is required for the following code
|
||||
base.send(:class_inheritable_accessor, :design_doc)
|
||||
base.send(:class_inheritable_accessor, :design_doc_slug_cache)
|
||||
base.send(:class_inheritable_accessor, :design_doc_fresh)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
||||
# Define a CouchDB view. The name of the view will be the concatenation
|
||||
# of <tt>by</tt> and the keys joined by <tt>_and_</tt>
|
||||
#
|
||||
# ==== Example views:
|
||||
#
|
||||
# class Post
|
||||
# # view with default options
|
||||
# # query with Post.by_date
|
||||
# view_by :date, :descending => true
|
||||
#
|
||||
# # view with compound sort-keys
|
||||
# # query with Post.by_user_id_and_date
|
||||
# view_by :user_id, :date
|
||||
#
|
||||
# # view with custom map/reduce functions
|
||||
# # query with Post.by_tags :reduce => true
|
||||
# view_by :tags,
|
||||
# :map =>
|
||||
# "function(doc) {
|
||||
# if (doc['couchrest-type'] == 'Post' && doc.tags) {
|
||||
# doc.tags.forEach(function(tag){
|
||||
# emit(doc.tag, 1);
|
||||
# });
|
||||
# }
|
||||
# }",
|
||||
# :reduce =>
|
||||
# "function(keys, values, rereduce) {
|
||||
# return sum(values);
|
||||
# }"
|
||||
# end
|
||||
#
|
||||
# <tt>view_by :date</tt> will create a view defined by this Javascript
|
||||
# function:
|
||||
#
|
||||
# function(doc) {
|
||||
# if (doc['couchrest-type'] == 'Post' && doc.date) {
|
||||
# emit(doc.date, null);
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# It can be queried by calling <tt>Post.by_date</tt> which accepts all
|
||||
# valid options for CouchRest::Database#view. In addition, calling with
|
||||
# the <tt>:raw => true</tt> option will return the view rows
|
||||
# themselves. By default <tt>Post.by_date</tt> will return the
|
||||
# documents included in the generated view.
|
||||
#
|
||||
# CouchRest::Database#view options can be applied at view definition
|
||||
# time as defaults, and they will be curried and used at view query
|
||||
# time. Or they can be overridden at query time.
|
||||
#
|
||||
# Custom views can be queried with <tt>:reduce => true</tt> to return
|
||||
# reduce results. The default for custom views is to query with
|
||||
# <tt>:reduce => false</tt>.
|
||||
#
|
||||
# Views are generated (on a per-model basis) lazily on first-access.
|
||||
# This means that if you are deploying changes to a view, the views for
|
||||
# that model won't be available until generation is complete. This can
|
||||
# take some time with large databases. Strategies are in the works.
|
||||
#
|
||||
# To understand the capabilities of this view system more compeletly,
|
||||
# it is recommended that you read the RSpec file at
|
||||
# <tt>spec/core/model_spec.rb</tt>.
|
||||
|
||||
def view_by(*keys)
|
||||
self.design_doc ||= Design.new(default_design_doc)
|
||||
opts = keys.pop if keys.last.is_a?(Hash)
|
||||
opts ||= {}
|
||||
ducktype = opts.delete(:ducktype)
|
||||
unless ducktype || opts[:map]
|
||||
opts[:guards] ||= []
|
||||
opts[:guards].push "(doc['couchrest-type'] == '#{self.to_s}')"
|
||||
end
|
||||
keys.push opts
|
||||
self.design_doc.view_by(*keys)
|
||||
self.design_doc_fresh = false
|
||||
end
|
||||
|
||||
# returns stored defaults if the there is a view named this in the design doc
|
||||
def has_view?(view)
|
||||
view = view.to_s
|
||||
design_doc && design_doc['views'] && design_doc['views'][view]
|
||||
end
|
||||
|
||||
# Dispatches to any named view.
|
||||
def view name, query={}, &block
|
||||
unless design_doc_fresh
|
||||
refresh_design_doc
|
||||
end
|
||||
query[:raw] = true if query[:reduce]
|
||||
raw = query.delete(:raw)
|
||||
fetch_view_with_docs(name, query, raw, &block)
|
||||
end
|
||||
|
||||
def all_design_doc_versions
|
||||
database.documents :startkey => "_design/#{self.to_s}-",
|
||||
:endkey => "_design/#{self.to_s}-\u9999"
|
||||
end
|
||||
|
||||
# Deletes any non-current design docs that were created by this class.
|
||||
# Running this when you're deployed version of your application is steadily
|
||||
# and consistently using the latest code, is the way to clear out old design
|
||||
# docs. Running it to early could mean that live code has to regenerate
|
||||
# potentially large indexes.
|
||||
def cleanup_design_docs!
|
||||
ddocs = all_design_doc_versions
|
||||
ddocs["rows"].each do |row|
|
||||
if (row['id'] != design_doc_id)
|
||||
database.delete_doc({
|
||||
"_id" => row['id'],
|
||||
"_rev" => row['value']['rev']
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_view_with_docs name, opts, raw=false, &block
|
||||
if raw
|
||||
fetch_view name, opts, &block
|
||||
else
|
||||
begin
|
||||
view = fetch_view name, opts.merge({:include_docs => true}), &block
|
||||
view['rows'].collect{|r|new(r['doc'])} if view['rows']
|
||||
rescue
|
||||
# fallback for old versions of couchdb that don't
|
||||
# have include_docs support
|
||||
view = fetch_view name, opts, &block
|
||||
view['rows'].collect{|r|new(database.get(r['id']))} if view['rows']
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_view view_name, opts, &block
|
||||
retryable = true
|
||||
begin
|
||||
design_doc.view(view_name, opts, &block)
|
||||
# the design doc could have been deleted by a rouge process
|
||||
rescue RestClient::ResourceNotFound => e
|
||||
if retryable
|
||||
refresh_design_doc
|
||||
retryable = false
|
||||
retry
|
||||
else
|
||||
raise e
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end # module ClassMethods
|
||||
|
||||
|
||||
end
|
||||
end
|
||||
end
|
55
lib/couchrest/validation/contextual_validators.rb
Normal file
55
lib/couchrest/validation/contextual_validators.rb
Normal file
|
@ -0,0 +1,55 @@
|
|||
module CouchRest
|
||||
module Validation
|
||||
|
||||
##
|
||||
#
|
||||
# @author Guy van den Berg
|
||||
# @since 0.9
|
||||
class ContextualValidators
|
||||
|
||||
def dump
|
||||
contexts.each_pair do |key, context|
|
||||
puts "Key=#{key} Context: #{context}"
|
||||
end
|
||||
end
|
||||
|
||||
# Get a hash of named context validators for the resource
|
||||
#
|
||||
# @return <Hash> a hash of validators <GenericValidator>
|
||||
def contexts
|
||||
@contexts ||= {}
|
||||
end
|
||||
|
||||
# Return an array of validators for a named context
|
||||
#
|
||||
# @return <Array> An array of validators
|
||||
def context(name)
|
||||
contexts[name] ||= []
|
||||
end
|
||||
|
||||
# Clear all named context validators off of the resource
|
||||
#
|
||||
def clear!
|
||||
contexts.clear
|
||||
end
|
||||
|
||||
# Execute all validators in the named context against the target
|
||||
#
|
||||
# @param <Symbol> named_context the context we are validating against
|
||||
# @param <Object> target the resource that we are validating
|
||||
# @return <Boolean> true if all are valid, otherwise false
|
||||
def execute(named_context, target)
|
||||
raise(ArgumentError, 'invalid context specified') if !named_context || (contexts.length > 0 && !contexts[named_context])
|
||||
target.errors.clear!
|
||||
result = true
|
||||
context(named_context).each do |validator|
|
||||
next unless validator.execute?(target)
|
||||
result = false unless validator.call(target)
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
end # module ContextualValidators
|
||||
end # module Validation
|
||||
end # module CouchRest
|
118
lib/couchrest/validation/validation_errors.rb
Normal file
118
lib/couchrest/validation/validation_errors.rb
Normal file
|
@ -0,0 +1,118 @@
|
|||
# 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 ValidationErrors
|
||||
|
||||
include Enumerable
|
||||
|
||||
@@default_error_messages = {
|
||||
:absent => '%s must be absent',
|
||||
:inclusion => '%s must be one of [%s]',
|
||||
:invalid => '%s has an invalid format',
|
||||
:confirmation => '%s does not match the confirmation',
|
||||
:accepted => "%s is not accepted",
|
||||
:nil => '%s must not be nil',
|
||||
:blank => '%s must not be blank',
|
||||
:length_between => '%s must be between %s and %s characters long',
|
||||
:too_long => '%s must be less than %s characters long',
|
||||
:too_short => '%s must be more than %s characters long',
|
||||
:wrong_length => '%s must be %s characters long',
|
||||
:taken => '%s is already taken',
|
||||
:not_a_number => '%s must be a number',
|
||||
:not_an_integer => '%s must be an integer',
|
||||
:greater_than => '%s must be greater than %s',
|
||||
:greater_than_or_equal_to => "%s must be greater than or equal to %s",
|
||||
:equal_to => "%s must be equal to %s",
|
||||
:less_than => '%s must be less than %s',
|
||||
:less_than_or_equal_to => "%s must be less than or equal to %s",
|
||||
:value_between => '%s must be between %s and %s',
|
||||
:primitive => '%s must be of type %s'
|
||||
}
|
||||
|
||||
# Holds a hash with all the default error messages that can be replaced by your own copy or localizations.
|
||||
cattr_writer :default_error_messages
|
||||
|
||||
def self.default_error_message(key, field, *values)
|
||||
field = Extlib::Inflection.humanize(field)
|
||||
@@default_error_messages[key] % [field, *values].flatten
|
||||
end
|
||||
|
||||
# Clear existing validation errors.
|
||||
def clear!
|
||||
errors.clear
|
||||
end
|
||||
|
||||
# Add a validation error. Use the field_name :general if the errors does
|
||||
# not apply to a specific field of the Resource.
|
||||
#
|
||||
# @param <Symbol> field_name the name of the field that caused the error
|
||||
# @param <String> message the message to add
|
||||
def add(field_name, message)
|
||||
(errors[field_name] ||= []) << message
|
||||
end
|
||||
|
||||
# Collect all errors into a single list.
|
||||
def full_messages
|
||||
errors.inject([]) do |list, pair|
|
||||
list += pair.last
|
||||
end
|
||||
end
|
||||
|
||||
# Return validation errors for a particular field_name.
|
||||
#
|
||||
# @param <Symbol> field_name the name of the field you want an error for
|
||||
def on(field_name)
|
||||
errors_for_field = errors[field_name]
|
||||
errors_for_field.blank? ? nil : errors_for_field
|
||||
end
|
||||
|
||||
def each
|
||||
errors.map.each do |k, v|
|
||||
next if v.blank?
|
||||
yield(v)
|
||||
end
|
||||
end
|
||||
|
||||
def empty?
|
||||
entries.empty?
|
||||
end
|
||||
|
||||
def method_missing(meth, *args, &block)
|
||||
errors.send(meth, *args, &block)
|
||||
end
|
||||
|
||||
private
|
||||
def errors
|
||||
@errors ||= {}
|
||||
end
|
||||
|
||||
end # class ValidationErrors
|
||||
end # module Validation
|
||||
end # module CouchRest
|
|
@ -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
|
|
@ -2,6 +2,7 @@ require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper')
|
|||
|
||||
# check the following file to see how to use the spec'd features.
|
||||
require File.join(FIXTURE_PATH, 'more', 'card')
|
||||
require File.join(FIXTURE_PATH, 'more', 'invoice')
|
||||
|
||||
describe "ExtendedDocument properties" do
|
||||
|
||||
|
@ -33,11 +34,37 @@ describe "ExtendedDocument properties" do
|
|||
@card.family_name.should == @card.last_name
|
||||
end
|
||||
|
||||
it "should be able to be validated" do
|
||||
pending("need to add validation") do
|
||||
describe "validation" do
|
||||
|
||||
before(:each) do
|
||||
@invoice = Invoice.new(:client_name => "matt", :employee_name => "Chris", :location => "San Diego, CA")
|
||||
end
|
||||
|
||||
it "should be able to be validated" do
|
||||
@card.should be_valid
|
||||
end
|
||||
#Card.property(:company, :required => true)
|
||||
|
||||
it "should let you validate the presence of an attribute" do
|
||||
@card.first_name = nil
|
||||
@card.should_not be_valid
|
||||
@card.errors.should_not be_empty
|
||||
@card.errors.on(:first_name).should == ["First name must not be blank"]
|
||||
end
|
||||
|
||||
it "should validate the presence of 2 attributes" do
|
||||
@invoice.clear
|
||||
@invoice.should_not be_valid
|
||||
@invoice.errors.should_not be_empty
|
||||
@invoice.errors.on(:client_name).should == ["Client name must not be blank"]
|
||||
@invoice.errors.on(:employee_name).should_not be_empty
|
||||
end
|
||||
|
||||
it "should let you set an error message" do
|
||||
@invoice.location = nil
|
||||
@invoice.valid?
|
||||
@invoice.errors.on(:location).first.should == "Hey stupid!, you forgot the location"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
9
spec/fixtures/more/card.rb
vendored
9
spec/fixtures/more/card.rb
vendored
|
@ -1,7 +1,16 @@
|
|||
class Card < CouchRest::ExtendedDocument
|
||||
# Include the validation module to get access to the validation methods
|
||||
include CouchRest::Validation
|
||||
|
||||
# Set the default database to use
|
||||
use_database TEST_SERVER.default_database
|
||||
|
||||
# Official Schema
|
||||
property :first_name
|
||||
property :last_name, :alias => :family_name
|
||||
property :read_only_value, :read_only => true
|
||||
|
||||
# Validation
|
||||
validates_present :first_name
|
||||
|
||||
end
|
17
spec/fixtures/more/invoice.rb
vendored
Normal file
17
spec/fixtures/more/invoice.rb
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
class Invoice < CouchRest::ExtendedDocument
|
||||
# Include the validation module to get access to the validation methods
|
||||
include CouchRest::Validation
|
||||
|
||||
# Set the default database to use
|
||||
use_database TEST_SERVER.default_database
|
||||
|
||||
# Official Schema
|
||||
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
|
Loading…
Reference in a new issue