From c3fa5c3d25d9148d2806db577a2261032b341c34 Mon Sep 17 00:00:00 2001 From: kakipo Date: Sun, 3 Aug 2014 14:50:09 +0900 Subject: Allow symbol as values for `tokenize` of `LengthValidator` --- activemodel/lib/active_model/validations/length.rb | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'activemodel/lib') diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb index a96b30cadd..c63a9d74b3 100644 --- a/activemodel/lib/active_model/validations/length.rb +++ b/activemodel/lib/active_model/validations/length.rb @@ -38,7 +38,7 @@ module ActiveModel end def validate_each(record, attribute, value) - value = tokenize(value) + value = tokenize(record, value) value_length = value.respond_to?(:length) ? value.length : value.to_s.length errors_options = options.except(*RESERVED_OPTIONS) @@ -59,10 +59,14 @@ module ActiveModel end private - - def tokenize(value) - if options[:tokenizer] && value.kind_of?(String) - options[:tokenizer].call(value) + def tokenize(record, value) + tokenizer = options[:tokenizer] + if tokenizer && value.kind_of?(String) + if tokenizer.kind_of?(Proc) + tokenizer.call(value) + elsif record.respond_to?(tokenizer) + record.send(tokenizer, value) + end end || value end @@ -108,8 +112,8 @@ module ActiveModel # * :message - The error message to use for a :minimum, # :maximum, or :is violation. An alias of the appropriate # too_long/too_short/wrong_length message. - # * :tokenizer - Specifies how to split up the attribute string. - # (e.g. tokenizer: ->(str) { str.scan(/\w+/) } to count words + # * :tokenizer - Specifies a method, proc or string to how to split up the attribute string. + # (e.g. tokenizer: ->(str) { str.scan(/\w+/) } or tokenizer: :word_tokenizer to count words # as in above example). Defaults to ->(value) { value.split(//) } # which counts individual characters. # -- cgit v1.2.3