Module: Viitelaskuri
- Extended by:
- Viitelaskuri
- Included in:
- Viitelaskuri
- Defined in:
- lib/viitelaskuri.rb,
lib/viitelaskuri/version.rb
Overview
A collection of methods for calculating bank references for finnish invoices.
Constant Summary collapse
- Version =
'0.1.0'
Instance Method Summary collapse
-
#calculate(seed) ⇒ Integer
Calculates the bank reference for a given number.
-
#format(ref) ⇒ String
Formats a given number into five digit groups starting from the right.
-
#generate ⇒ Integer
Generates an almost certainly unique bank reference.
-
#valid?(ref) ⇒ Boolean
Checks if a given number is a valid bank reference.
Instance Method Details
#calculate(seed) ⇒ Integer
Calculates the bank reference for a given number
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/viitelaskuri.rb', line 13 def calculate(seed) str = seed.to_s if str.length < 3 raise ArgumentError.new('The seed must be at least 3 digits.') end if str.length > 19 raise ArgumentError.new('The seed must not be more than 19 digits.') end reversed = str.reverse sum = 0 coefficients = [7, 3, 1] i = 0 reversed.each_char do |c| n = c.to_i sum += n * coefficients[i % 3] i += 1 end # sum -> nearest full ten - sum check = sum % 10 == 0 ? 0 : ((sum / 10).to_i + 1) * 10 - sum str = str + check.to_s str.to_i end |
#format(ref) ⇒ String
Formats a given number into five digit groups starting from the right
44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/viitelaskuri.rb', line 44 def format(ref) str = ref.to_s if str.length < 4 raise ArgumentError.new('The seed must be at least 4 digits.') end if str.length > 20 raise ArgumentError.new('The seed must not be more than 20 digits.') end # organize in five letter groups starting from the right in_groups_of(str.reverse.split(''), 5, false).map { |e| e.join('') }.join(' ').reverse end |
#generate ⇒ Integer
Generates an almost certainly unique bank reference. Uses a timestamp (10 digits) and a random number (9 digits) and adds the check number.
77 78 79 80 81 |
# File 'lib/viitelaskuri.rb', line 77 def generate time = Time.now.utc.to_i random = 9.times.map { rand(10) } calculate(time.to_s + random.to_s) end |
#valid?(ref) ⇒ Boolean
Checks if a given number is a valid bank reference
63 64 65 66 67 68 69 70 |
# File 'lib/viitelaskuri.rb', line 63 def valid?(ref) if ref.to_s.length < 4 || ref.to_s.length > 20 return false end str = ref.to_s[0...-1] calculate(str) == ref.to_i end |