Class: ReferenceNumber

Inherits:
Object
  • Object
show all
Defined in:
lib/reference_number.rb,
lib/reference_number/version.rb

Defined Under Namespace

Classes: InvalidReferenceNumber

Constant Summary collapse

VERSION =
"1.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, opts = { :zero_padding => false }) ⇒ ReferenceNumber

Returns a new instance of ReferenceNumber.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/reference_number.rb', line 7

def initialize(input, opts = { :zero_padding => false })
  @zero_padding = opts[:zero_padding]
  
  @input = input
  if(@input.is_a? Integer)
    @input = @input.to_s
  end

  raise InvalidReferenceNumber, "Input should be between 3 to 19 characters long" if (@input.length < 3 || @input.length > 19)
  raise InvalidReferenceNumber, "Only spaces and numbers are allowed" if (@input =~ /[^ \d]/) != nil

  @input.gsub!(/ /, "")
  @input.sub!(/0*/, "") # remove leading zeros

  raise InvalidReferenceNumber, "Input can't be just spaces and zeroes." if(@input.length == 0)
end

Instance Attribute Details

#inputObject

Returns the value of attribute input.



5
6
7
# File 'lib/reference_number.rb', line 5

def input
  @input
end

Instance Method Details

#to_s(options = { :zero_padding => false }) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/reference_number.rb', line 24

def to_s(options = { :zero_padding => false })
  @input.reverse!
  base = "731" * 50

  index = 0
  sum   = 0

  @input.each_byte do |b|
    result = b.chr.to_i * base[index % 3].chr.to_i
    sum = sum + result
    index = index + 1
  end

  # Calculate the last number. If sum = 94 then number is 6.
  difference = (10 - (sum % 10)) % 10
  difference_and_input = "#{difference}#{@input}".reverse

  if @zero_padding
    "%020d" % difference_and_input if @zero_padding
  else
    difference_and_input
  end
end