Revisions

gist: 135311 Download_button fork
public
Public Clone URL: git://gist.github.com/135311.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
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
38
39
40
41
42
43
44
45
# This allows generation of "codes"... namely for part-numbers and unique identifiers for records
# It's especially effective with FactoryGirl's sequences.
#
# Examples:
# Factory.define :whatever do |whatever|
# whatever.sequence(:unique_code) {|n| generate_code(n, :length => 4, :numeric => true) }
# # ...
# end
#
# Factory.define :another do |another|
# another.sequence(:code) {|n| generate_code(n, :length => 2) }
# # ...
# end
#
# By default, it generates alphanumeric codes of length 1 (meaning at the 37th sequence, it'll reset to A)
# It accepts the options :length, :alpha, and :numeric
#
# Results:
#
# generate_code 36, :length => 2 # "BA"
# generate_code 170, :length => 3, :numeric => true # "170"
# generate_code 45200, :length => 4, :alpha => true # "COWM"
#
def generate_code(n, options = {})
  available = []
  code_length = options[:length] || 1
 
  available << if options[:numeric]
    ("0".."9").map
  elsif options[:alpha]
    ("A".."Z").map
  else
    ("A".."Z").map + ("0".."9").map
  end
 
  available.flatten!
  result = ""
 
  while code_length > 0
    result << (available)[(n/(available.length**(code_length - 1))).to_i % available.length]
    code_length -= 1
  end
 
  result
end