Created
February 23, 2010 19:15
-
-
Save reactormonk/312571 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| module DataMapper | |
| module Validate | |
| class SizeValidator < GenericValidator | |
| def call(target) | |
| return true if valid?(target) | |
| # Copied from within_validator | |
| size = @options[:size] | |
| msg = @options[:message] | |
| if size.is_a?(Range) | |
| if size.first != -n && size.last != n | |
| error_message = msg || ValidationErrors.default_error_message(:value_between, field_name, size.first, size.last) | |
| elsif size.first == -n | |
| error_message = msg || ValidationErrors.default_error_message(:less_than_or_equal_to, field_name, size.last) | |
| elsif size.last == n | |
| error_message = msg || ValidationErrors.default_error_message(:greater_than_or_equal_to, field_name, size.first) | |
| end | |
| else | |
| error_message = msg || ValidationErrors.default_error_message(:value, field_name, size.join(', ')) | |
| end | |
| add_error(target, error_message, field_name) | |
| false | |
| end | |
| private | |
| def valid?(target) | |
| return true if optional?(value) | |
| @options[:size] === target.size | |
| end | |
| end | |
| module ValidatesSize | |
| ## | |
| # Validates that the number of the specified association (or attribute) | |
| # is within the range. | |
| # | |
| # @example [Usage] | |
| # | |
| # class WikiPage | |
| # include DataMapper::Resource | |
| # | |
| # # proposed API | |
| # has (5..n), :citations | |
| # | |
| # # current API | |
| # has n, :citations | |
| # validates_size :citations, :size => (5..n) | |
| # | |
| # end | |
| # | |
| def validates_size(*fields) | |
| opts = opts_from_validator_args(fields) | |
| add_validator_to_context(opts, fields, DataMapper::Validate::SizeValidator) | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment