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.
Add this line to your application's Gemfile:
gem 'unique_attributes'
And then execute:
$ bundle
Or install it yourself as:
$ gem install unique_attributes
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
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?)
- Fork it (https://github.com/panorama-ed/unique_attributes/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - 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.
UniqueAttributes is released under the MIT License.