I’ve just released a new ruby gem called SimpleUnique that adds a ‘validates_uniqueness_of’ method to the AWS::Record::Model class provided by ‘aws-sdk’.  This allows you to do things like garauntee unique usernames.  Like many things in life, SimpleUnique is not perfect, and using it does include some caveats that you should consider.  Read the whole post to learn more.

Important Links

First things first. You can find SimpleUniqe on RubyGems, and the source code lives at GitHub.

Installation

To use the gem just add this to your Gemfile

gem "simple_unique", "~> 0.0.1"

The run

$ bundle install

Usage

In any of your models that inherit from AWS::Record::Model you can do something like this:

validates_uniqueness_of :foo

You can also include a scope for the validation, if for instance you wanted to keep a foo unique within a given bar.

validates_uniqueness_of :foo, :scope => :bar_id

You can also use the :if and :unless options to run the validation on a conditional basis.

validates_uniqueness_of :foo, :if => :should_validate_foo

def should_validate_foo
  rand(100) == 42
end

Of course, you’ll probably want something better than a random number generator as your condition.

Caveats

Using this validation method in conjunction with AWS::Record::Model#save does not guarantee the absence of duplicate record insertions, because checking SimpleDB over the network takes some time, and a duplicate record may be inserted in the time that elapses between the check and the record insertion. SimpleDB itself also experiences a bit of a propagation delay on record changes.

So, this means that this validation is inherently un-reliable. It is probably best suited for systems where validation events will be relatively few and far between. For instance in small private/internal systems where the number of new users over time will be very low, it should work well to guarantee that a given email address is unique. Conversely, in a public facing systems with open registration it would not work well to guarantee the uniqueness of usernames.

If you make use of this in a system with a relatively high rate of record creation you may want to create a process to periodically scan your domain for duplicate records and then take action in a way that makes sense for your system.

BTW, if you’re interested in using SimpleDB for user registration, you should checkout my post Using SimpleDB with Devise : Part 1. Part 2 will be coming soon and will cover the addition of SimpleUnique to the project that was started in Part 1.