Class: CreditCardValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/valid_credit_card/credit_card_validator.rb

Instance Method Summary collapse

Instance Method Details

#default_optionsObject



7
8
9
# File 'lib/valid_credit_card/credit_card_validator.rb', line 7

def default_options
  { card_types: ValidCreditCard::CreditCard::CARD_TYPES.keys.map(&:to_s) }
end

#error(record, attribute) ⇒ Object



23
24
25
# File 'lib/valid_credit_card/credit_card_validator.rb', line 23

def error(record, attribute)
  record.errors.add(attribute, options[:message] || :invalid)
end

#validate_each(record, attribute, value) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/valid_credit_card/credit_card_validator.rb', line 11

def validate_each(record, attribute, value)
  return unless value.present?

  options = default_options.merge(self.options)

  cc = ValidCreditCard::CreditCard.new(value)

  error(record, attribute) && return unless cc.valid?

  error(record, attribute) && return unless options[:card_types].include?(cc.card_type)
end