Code Climate Test Coverage Inline docs Build Status Gem Version

UniqueAttributes

UniqueAttributes gives you an easy way to ensure that autogenerated fields on your ActiveRecord models are unique.

Auto-assign usernames for your users? You've come to the right place.

Installation

Add this line to your application's Gemfile:

gem 'unique_attributes'

And then execute:

$ bundle

Or install it yourself as:

$ gem install unique_attributes

Usage

require "unique_attributes"

class User < ActiveRecord::Base
  include UniqueAttributes

  unique_attribute :username, proc { SecureRandom.hex }
end

VoilĂ ! Now let's see how it works:

> user = User.new
> user.username
=> nil
> user.save!
> user.username
=> "1a4523822c1a2bebdfc0c036c94f1e0e"

Your user now has a username that's automatically set via the proc you specify, and it's guaranteed to be unique among all users.

You can still change the value at any time:

> user.username = "Grace Hopper"
> user.save!
> user.username
=> "Grace Hopper"

What if the uniqueness is scoped by something? No problem:

unique_attribute :username, proc { SecureRandom.hex }, scope: :group_id

You can pass in any scopes you could pass into a Rails uniqueness validation. Now:

> user1 = User.new(group_id: 1)
> user2 = User.new(group_id: 1)
> user3 = User.new(group_id: 2)

Because user1 and user2 are in the same uniqueness scope, we are guaranteed to give them different usernames. user3 could have the same username as either of them since it's outside the uniqueness scope.


Note that UniqueAttributes assumes you have an accompanying unique index in your database:

add_index :users, :username, unique: true

or, in the case of a scoped uniqueness:

add_index :users, [:username, :group_id], unique: true

Database Compatibility

UniqueAttributes currently supports PostgreSQL and SQLite3, though adding support for your favorite database adapter is as easy as writing a regex to parse its uniqueness violation error messages. (Note that MySQL's messages do not give granular enough output and thus are not supported currently. Maybe you can come up with a fix?)

Contributing

  1. Fork it (https://github.com/panorama-ed/unique_attributes/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Make sure your changes have appropriate tests (bundle exec rspec) and conform to the Rubocop style specified. We use overcommit to enforce good code.

License

UniqueAttributes is released under the MIT License.