Class: CrazyValidators::BlacklistValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/crazy_validators/blacklist_validator.rb

Constant Summary collapse

RESERVED_OPTIONS =
[:with_array, :with_model, :with_file, :type]
DEFAULT_FILE =
File.join(File.dirname(__FILE__), 'blacklist', 'default.yml')
DEFAULT_TYPE =
:equals

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ BlacklistValidator

Returns a new instance of BlacklistValidator.



11
12
13
# File 'lib/crazy_validators/blacklist_validator.rb', line 11

def initialize(options)
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/crazy_validators/blacklist_validator.rb', line 15

def validate_each(record, attribute, value)
  @blacklist = load_blacklist
  type = (options[:type] || DEFAULT_TYPE)
  error_options = options.except(RESERVED_OPTIONS)
  if type == :contains
    @blacklist.each do |el|
      if value.to_s.include? el
        error_options[:word] = value.to_s
        record.errors.add(attribute, :contains_blacklist, error_options)
        break
      end
    end
  else
    value.to_s.split(/'| /).each do |el|
      if @blacklist.include? el
        error_options[:word] = el.to_s
        record.errors.add(attribute, :in_blacklist, error_options)
        break
      end
    end
  end
end