Class: ActiveModel::Validations::StrengthValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/password_strength/active_model.rb

Overview

:nodoc: all

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ StrengthValidator

Returns a new instance of StrengthValidator.



4
5
6
# File 'lib/password_strength/active_model.rb', line 4

def initialize(options)
  super(options.reverse_merge(:level => :good, :with => :username, :using => PasswordStrength::Base))
end

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


18
19
20
21
22
23
# File 'lib/password_strength/active_model.rb', line 18

def check_validity!
  raise ArgumentError, "The :with option must be supplied" unless options.include?(:with)
  raise ArgumentError, "The :exclude options must be an array of strings or a regular expression" if options[:exclude] && !options[:exclude].kind_of?(Array) && !options[:exclude].kind_of?(Regexp)
  check_level_validity!(options[:level])
  super
end

#level(record) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/password_strength/active_model.rb', line 25

def level(record)
  if options[:level].respond_to?(:call)
    level = options[:level].call(record).to_sym
    check_level_validity!(level)
    level
  else
    options[:level]
  end
end

#validate_each(record, attribute, value) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/password_strength/active_model.rb', line 8

def validate_each(record, attribute, value)
  return unless PasswordStrength.enabled
  strength = options[:using].new(record.send(options[:with]), value,
    :exclude => options[:exclude],
    :record => record
  )
  strength.test
  record.errors.add(attribute, :too_weak, options) unless PasswordStrength.enabled && strength.valid?(level(record))
end