Created
November 17, 2011 01:41
-
-
Save tjhayasaka/1372116 to your computer and use it in GitHub Desktop.
modify Rails 3.0 LengthValidator to accept Proc objects as length-limit and message options
This file contains 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
# | |
# modify LengthValidator to accept Proc objects as length-limit and message options | |
module ActiveModel | |
# == Active Model Length Validator | |
module Validations | |
class LengthValidator | |
def initialize(options) | |
if range = (options.delete(:in) || options.delete(:within)) | |
options[:within] = range | |
raise ArgumentError, ":in and :within must be a Range or a Proc" unless range.is_a?(Range) || range.is_a?(Proc) | |
end | |
super(options.reverse_merge(:tokenizer => DEFAULT_TOKENIZER)) | |
end | |
def gather_options | |
tmp_options = Hash[options] # make a unfrozen copy of options | |
range = tmp_options[:within] | |
if range | |
range = range.call if range.is_a?(Proc) | |
raise ArgumentError, ":in and :within must be a Range or a Proc" unless range.is_a?(Range) | |
tmp_options[:minimum], tmp_options[:maximum] = range.begin, range.end | |
tmp_options[:maximum] -= 1 if range.exclude_end? | |
end | |
tmp_options[:minimum] = tmp_options[:minimum].call if tmp_options[:minimum].is_a?(Proc) | |
tmp_options[:maximum] = tmp_options[:maximum].call if tmp_options[:maximum].is_a?(Proc) | |
tmp_options | |
end | |
def check_validity! | |
true # FIXME: no load-time sanity checks??? | |
end | |
def validate_each(record, attribute, value) | |
tmp_options = gather_options | |
value = options[:tokenizer].call(value) if value.kind_of?(String) | |
CHECKS.each do |key, validity_check| | |
next unless check_value = tmp_options[key] | |
value ||= [] if key == :maximum | |
next if value && value.size.send(validity_check, check_value) | |
errors_options = options.except(*RESERVED_OPTIONS) | |
errors_options[:count] = check_value | |
default_message = options[MESSAGES[key]] | |
errors_options[:message] ||= default_message if default_message | |
errors_options[:message] = errors_options[:message].call if errors_options[:message].is_a?(Proc) | |
record.errors.add(attribute, MESSAGES[key], errors_options) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment