pretty_id

Travis Code Climate Coveralls RubyGem

Add random, unique "pretty" ids to your ActiveRecord models.

Usage

1. Install the gem

gem 'pretty_id'

2. Add a pretty_id column (and index!) to your model

add_column :books, :pretty_id, :string
add_index :books, :pretty_id

3. Add has_pretty_id to your model

class Book < ActiveRecord::Base
  has_pretty_id
end

Generation methods

:pretty (default)

chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
Array.new(options[:length]) { chars[rand(chars.length)] }.join

:urlsafe_base64

SecureRandom.urlsafe_base64(options[:length] / 1.333)

Options

class Book < ActiveRecord::Base
  has_pretty_id method: :urlsafe_base64,          # default: :pretty
                column: :another_string_column,   # default: :pretty_id
                length: 12,                       # default: 8
                uniq: false                       # default: true
end

Instance methods

#regenerate_#{column_name}

user = User.create
user.pretty_id # => 'a0923sdf'
user.regenerate_pretty_id
user.pretty_id # => 'lf91fs9s'

#regenerate_#{column_name}!

Same as above, but also calls save on the record