Class: CreditCardValidations::Detector

Inherits:
Object
  • Object
show all
Includes:
Mmi
Defined in:
lib/credit_card_validations/detector.rb

Constant Summary

Constants included from Mmi

Mmi::ISSUER_CATEGORIES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mmi

#issuer_category

Constructor Details

#initialize(number) ⇒ Detector

Returns a new instance of Detector.



11
12
13
# File 'lib/credit_card_validations/detector.rb', line 11

def initialize(number)
  @number = number.to_s.tr('- ', '')
end

Instance Attribute Details

#numberObject (readonly)

Returns the value of attribute number.



9
10
11
# File 'lib/credit_card_validations/detector.rb', line 9

def number
  @number
end

Class Method Details

.add_rule(brand, length, prefixes, skip_luhn = false) ⇒ Object

create rule for detecting brand



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/credit_card_validations/detector.rb', line 51

def add_rule(brand, length, prefixes, skip_luhn = false)
  prefixes = Array.wrap(prefixes)
  length = Array.wrap(length)
  rules[brand] = [] if rules[brand].blank?
  rules[brand] << {length: length, regexp: compile_regexp(prefixes), prefixes: prefixes, skip_luhn: skip_luhn}

  define_method "#{brand}?".to_sym do
    valid?(brand)
  end unless method_defined?  "#{brand}?".to_sym

  rules[brand]
end

.compile_regexp(prefixes) ⇒ Object

create regexp by array of prefixes



46
47
48
# File 'lib/credit_card_validations/detector.rb', line 46

def compile_regexp(prefixes)
  Regexp.new("^((#{prefixes.join(")|(")}))")
end

Instance Method Details

#brand(*brands) ⇒ Object

brand name



21
22
23
# File 'lib/credit_card_validations/detector.rb', line 21

def brand(*brands)
  valid_number?(*brands)
end

#valid?(*brands) ⇒ Boolean

credit card number

Returns:

  • (Boolean)


16
17
18
# File 'lib/credit_card_validations/detector.rb', line 16

def valid?(*brands)
  !!valid_number?(*brands)
end

#valid_luhn?Boolean

check if luhn valid

Returns:

  • (Boolean)


39
40
41
# File 'lib/credit_card_validations/detector.rb', line 39

def valid_luhn?
  @valid_luhn ||= Luhn.valid?(number)
end

#valid_number?(*brands) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/credit_card_validations/detector.rb', line 25

def valid_number?(*brands)
  number_length = number.length
  brand_rules = brands.blank? ? self.rules : self.rules.slice(*brands.map { |el| el.downcase })
  unless brand_rules.blank?
    brand_rules.each do |brand_name, rules|
      rules.each do |rule|
        return brand_name if ((rule[:skip_luhn] || valid_luhn?) and rule[:length].include?(number_length) and number.match(rule[:regexp]))
      end
    end
  end
  nil
end