class Viitenumero::FIViite
Attributes
number[R]
Public Class Methods
generate(base)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 25 def self.generate(base) base = (base || '').to_s.gsub(/\s+/, '') raise ArgumentError.new('must be a number') if base.match(/\A\d+\z/).nil? raise ArgumentError.new('must be between 3-19 chars long') if base.length < 3 || base.length > 19 FIViite.new(base + checksum(base)) end
new(s)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 9 def initialize(s) @number = format(s) end
random(length: 4)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 33 def self.random(length: 4) raise ArgumentError if length < 4 || length > 20 base = '' base_length = length - 1 base = rand(10**base_length).to_s while base.length != base_length generate(base.to_s) end
valid?(s)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 41 def self.valid?(s) FIViite.new(s).valid? end
Private Class Methods
checksum(base)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 74 def self.checksum(base) weights = [7, 3, 1] checksum, current_weight = 0, 0 base.split('').reverse.each do |digit| checksum += digit.to_i * weights[current_weight % 3] current_weight += 1 end ((10 - checksum % 10) % 10).to_s end
Public Instance Methods
machine_format()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 17 def machine_format number end
paper_format()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 13 def paper_format number.gsub(/.{5}(?=.)/, '\0 ') end
to_rf()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 49 def to_rf RFViite.generate(machine_format, add_fi_checksum: false) end
to_s()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 45 def to_s machine_format end
valid?()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 21 def valid? valid_format? and valid_length? and valid_checksum? end
Private Instance Methods
format(s)
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 55 def format(s) r = (s || '').to_s.gsub(/\s+/, '') r.slice!(0) while r[0] == '0' r end
valid_checksum?()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 69 def valid_checksum? last_digit = number[-1, 1] last_digit == self.class.checksum(number[0..-2]) end
valid_format?()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 61 def valid_format? !number.match(/\A\d+\z/).nil? end
valid_length?()
click to toggle source
# File lib/viitenumero/fi_viite.rb, line 65 def valid_length? number.length >= 4 && number.length <= 20 end