Class: NotShoutingValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates_not_shouting/not_shouting_validator.rb

Overview

this is not namespaced so that we can do

validates :body, not_shouting: true

Instance Method Summary collapse

Instance Method Details

#shouting?(value) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
# File 'lib/validates_not_shouting/not_shouting_validator.rb', line 12

def shouting?(value)
  threshold = options.fetch(:threshold, 0.5)
  (value.gsub(/[^A-Z]/, '').length.to_f / value.length) > threshold
end

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/validates_not_shouting/not_shouting_validator.rb', line 4

def validate_each(record, attribute, value)
  return true if value.blank?

  if shouting?(value)
    record.errors[attribute] << options.fetch(:message, "cannot be mostly caps. It's not polite to shout.")
  end
end