lib/banktools-se/ocr.rb in banktools-se-2.0.0 vs lib/banktools-se/ocr.rb in banktools-se-2.1.0

- old
+ new

@@ -1,6 +1,6 @@ -# http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/BG6070.pdf section 5.2 +# http://web.archive.org/web/20111216065227/http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/BG6070.pdf section 5.2 module BankTools module SE class OCR class InvalidOCR < StandardError; end @@ -11,14 +11,14 @@ class MustBeNumeric < InvalidOCR; end MIN_LENGTH = 2 MAX_LENGTH = 25 - def self.from_number(number, opts = {}) + def self.from_number(number, length_digit: false, pad: "") number = number.to_s - add_length_digit = opts.fetch(:length_digit, false) - pad = opts.fetch(:pad, "").to_s + add_length_digit = length_digit + pad = pad.to_s raise MustBeNumeric unless number.match(/\A\d+\z/) # Padding isn't something BGC specifies, but we needed it to support a legacy scheme. number += pad # Adding 2: 1 length digit, 1 check digit. @@ -32,14 +32,14 @@ end number_with_ocr end - def self.to_number(number, opts = {}) + def self.to_number(number, length_digit: false, pad: "") number = number.to_s - should_have_length_digit = opts.fetch(:length_digit, false) - strip_padding = opts.fetch(:pad, "").to_s + should_have_length_digit = length_digit + strip_padding = pad.to_s raise MustBeNumeric unless number.match(/\A\d+\z/) raise BadChecksum unless Utils.valid_luhn?(number) if should_have_length_digit @@ -58,9 +58,20 @@ end digits_to_chop += strip_padding.length number[0...-digits_to_chop] + end + + def self.find_all_in_string(string, length_digit: false, pad: "") + string.scan(/\d+/).select { |candidate| + begin + to_number(candidate, length_digit: length_digit, pad: pad) + true + rescue InvalidOCR + false + end + }.uniq end end end end