Created
June 24, 2009 14:52
-
-
Save joshuaclayton/135311 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment