Class: UpcGen::UpcGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/upc_gen/upc_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(seed) ⇒ UpcGenerator

Returns a new instance of UpcGenerator.



7
8
9
# File 'lib/upc_gen/upc_generator.rb', line 7

def initialize(seed)
  @seed = seed
end

Instance Method Details

#find_code_ending_on(n) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/upc_gen/upc_generator.rb', line 15

def find_code_ending_on(n)
  digits = n[0...-1]
  check = n[-1]
  n_random_digits(12 - n.length)
  candidate = EAN13.complete(n_random_digits(12 - digits.length) + digits)
  while(candidate[-1] != check)
    candidate = EAN13.complete(n_random_digits(12 - digits.length) + digits)
  end
  candidate
end

#generateObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/upc_gen/upc_generator.rb', line 26

def generate
  if @seed
    number_string = @seed
    random_position = :end
    unless number_string =~ /^\d*$/
      if number_string =~ /\d-/
        random_position = :forced_end
      end
      if number_string =~ /\d\./
        random_position = :start
      end
      number_string = number_string.match(/^\d+/)[0]
    end

    if number_string.length < 12
      if random_position == :start
        number_string += n_random_digits(12 - number_string.length)
      elsif random_position == :forced_end
        return find_code_ending_on(number_string)
      else
        number_string = n_random_digits(12 - number_string.length) + number_string
      end
    end
    EAN13.complete number_string
  else
    EAN13.complete n_random_digits(12)
  end
end

#n_random_digits(n) ⇒ Object



11
12
13
# File 'lib/upc_gen/upc_generator.rb', line 11

def n_random_digits(n)
  (1..n).map { rand(10) }.join
end