Class: ActiveModel::Validations::WordCountValidator
- Inherits:
-
EachValidator
- Object
- EachValidator
- ActiveModel::Validations::WordCountValidator
- Defined in:
- lib/active_model/validations/word_count.rb
Instance Method Summary collapse
- #base_options ⇒ Object
- #check_validity! ⇒ Object
-
#initialize(options) ⇒ WordCountValidator
constructor
Provide option defaults and normalize options.
- #options_for(current, expected) ⇒ Object
- #validate_each(record, attribute, value) ⇒ Object
- #word_count_for(value) ⇒ Object
Constructor Details
#initialize(options) ⇒ WordCountValidator
Provide option defaults and normalize options. This is done prior to check_validity! as options becomes frozen and check_validity! can only report errors but not modify the options.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/active_model/validations/word_count.rb', line 14 def initialize() [:min] = .delete(:minimum) if .has_key?(:minimum) [:max] = .delete(:maximum) if .has_key?(:maximum) [:max] ||= 100 [:min] ||= 0 [:strip_tags] = true unless .has_key?(:strip_tags) [:strip_punctuation] = true unless .has_key?(:strip_punctuation) if .has_key?(:in) range = [:in] if range.present? && range.respond_to?(:min) && range.respond_to?(:max) [:min], [:max] = range.min, range.max .delete :in end end super end |
Instance Method Details
#base_options ⇒ Object
53 54 55 |
# File 'lib/active_model/validations/word_count.rb', line 53 def .except(:in, :min, :max, :skip_max, :skip_min) end |
#check_validity! ⇒ Object
31 32 33 34 35 |
# File 'lib/active_model/validations/word_count.rb', line 31 def check_validity! raise ArgumentError, "You must provide a valid range for the number of words e.g. 2..100" if .has_key?(:in) raise ArgumentError, "The min value must respond to to_i" unless [:min].respond_to?(:to_i) raise ArgumentError, "The max value must respond to to_i" unless [:max].respond_to?(:to_i) end |
#options_for(current, expected) ⇒ Object
57 58 59 |
# File 'lib/active_model/validations/word_count.rb', line 57 def (current, expected) .merge :expected_count => expected, :actual_count => current end |
#validate_each(record, attribute, value) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/active_model/validations/word_count.rb', line 37 def validate_each(record, attribute, value) min_words, max_words = [:min].to_i, [:max].to_i value = ActionController::Base.helpers.(value).gsub(/ | /i, ' ') if [:strip_tags] value.gsub! /[.(),;:!?%#\$'"_+=\/-]*/, '' if [:strip_punctuation] count = word_count_for(value) if ![:skip_min] && count < min_words record.errors.add attribute, :too_few_words, (count, min_words) elsif ![:skip_max] && count > max_words record.errors.add attribute, :too_many_words, (count, max_words) end end |
#word_count_for(value) ⇒ Object
49 50 51 |
# File 'lib/active_model/validations/word_count.rb', line 49 def word_count_for(value) value.to_s.scan(/\w+/).size end |