In several apps I've worked on, we've wanted a way to create a unique string. For example, users cannot have duplicate email addresses. So when creating many users via the Factory pattern, email addresses inevitably end up being something like "barney#{rand(1000)}@foo.org".
This always leads to problems. UUIDs can be handy but then you have a 30 character long email address.
Why not just a global, app-level incrementor? (utilizing the Singleton pattern)
It will always output a unique integer, starting with the number 1. Multiple objects can use this, so long as they do not require "random" integers to be in a row, but rather simply unique.
Enough talk. Here's the code:
module Incrementor
def self.next
@counter ||= Incrementor::Counter.new
@counter.next
endclass Counter
def initialize
@i = 0
end
def next
@i += 1
end
end
end
In rails, you can throw that as 'incrementor.rb' in your config/initializers folder.
Usage:
=> Incrementor.next
=> 1
=> Incrementor.next
=> 2
...