Class: ActiveModel::Validations::CreditCardValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/evelpidon_validators/credit_card.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CreditCardValidator



10
11
12
13
14
15
16
17
# File 'lib/evelpidon_validators/credit_card.rb', line 10

def initialize(options)
  if options[:type]
    warn "The :type option has been deprecated, please use :type_attribute instead."
    options[:type_attribute] ||= options[:type]
  end

  super
end

Class Method Details

.valid_credit_card?(number, type) ⇒ Boolean



19
20
21
22
23
24
25
26
27
28
# File 'lib/evelpidon_validators/credit_card.rb', line 19

def self.valid_credit_card?(number, type)
  return false if number.nil?

  if type
    ::CreditCardValidator::Validator.options[:allowed_card_types] = [type.underscore.to_sym]
  else
    ::CreditCardValidator::Validator.options[:allowed_card_types] = nil
  end
  ::CreditCardValidator::Validator.valid?(number)
end

.valid_luhn?(number) ⇒ Boolean



30
31
32
# File 'lib/evelpidon_validators/credit_card.rb', line 30

def self.valid_luhn?(number)
  number.nil? ? true : ::CreditCardValidator::Validator.verify_luhn(number)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/evelpidon_validators/credit_card.rb', line 34

def validate_each(record, attribute, value)
  if options[:luhn_only]
    unless self.class.valid_luhn? value
      record.errors.add(attribute, :credit_card, options)
    end
  else
    type = record.send(options[:type_attribute]) if options[:type_attribute]
    unless self.class.valid_credit_card? value, type
      record.errors.add(attribute, :credit_card, options)
    end
  end
end