Module: Luhn
- Defined in:
- lib/luhn.rb,
lib/luhn/version.rb
Constant Summary collapse
- MIN_LENGTH =
2- VERSION =
"0.3.0"
Class Method Summary collapse
- .check_digit(partial_num) ⇒ Object
- .generate(length: 16, prefix: nil) ⇒ Object
- .valid?(digits) ⇒ Boolean
Class Method Details
.check_digit(partial_num) ⇒ Object
14 15 16 |
# File 'lib/luhn.rb', line 14 def check_digit(partial_num) (10 - (non_checksum_sum(partial_num) % 10)) % 10 end |
.generate(length: 16, prefix: nil) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/luhn.rb', line 18 def generate(length: 16, prefix: nil) raise ArgumentError, 'length must be more than minimum' unless length.to_i > MIN_LENGTH raise ArgumentError, 'prefix length invalid' if prefix && (prefix.to_s.length + MIN_LENGTH >= length) raise ArgumentError, 'prefix must be numeric' if prefix && !numeric_string?(prefix) partial_num = (prefix&.empty? ? '' : prefix).to_s (length - 1 - partial_num.length).times do partial_num += rand(10).to_s end mod = 10 - (non_checksum_sum(partial_num) % 10) checksum = (mod == 10 ? 0 : mod).to_s partial_num + checksum end |
.valid?(digits) ⇒ Boolean
6 7 8 9 10 11 12 13 |
# File 'lib/luhn.rb', line 6 def valid?(digits) return false unless numeric_string?(digits) checksum = digits[-1].to_i non_checksum = non_checksum_sum(digits.chop) sum = checksum + non_checksum sum % 10 == 0 end |