Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Generates string tokens as alternative IDs for easy reference.

branch: master
README.md

Overview

Gem Version Code Climate GPA Gemnasium Status Travis CI Status Coverage Status

Generates string tokens as alternative IDs for easy reference. This can prove useful for URL addresses, internal code lookup, human readability, file system files, etc.

Features

  • Supports ActiveRecord models.
  • Supports token generation from single/multiple source attributes (including delimiter customization).
  • Supports custom token attribute naming in case the default "token" attribute is not desired.
  • Supports scopes for token generation and customization.
  • Supports duplicate token detection with suffix auto-generation (i.e. "-20110101235500") if desired.
  • Supports token validation using the same criteria as token generation.
  • Supports finding a record based on the token value, otherwise defaulting to the original ID.
  • Supports rebuilding of tokens either forcefully or gracefully.
  • Supports the detokenization of a tokenized string.

Requirements

  1. Any of the following Ruby VMs:
  2. Ruby on Rails 4.x.x.

Setup

For a secure install, type the following from the command line (recommended):

gem cert --add <(curl -Ls http://www.redalchemist.com/gem-public.pem)
gem install tokener --trust-policy MediumSecurity

NOTE: A HighSecurity trust policy would be best but MediumSecurity enables signed gem verification while allowing the installation of unsigned dependencies since they are beyond the scope of this gem.

For an insecure install, type the following (not recommended):

gem install tokener

Add the following to your Gemfile:

gem "tokener"

Usage

The are many options available to you, see below.

Basic

Basic, out-of-the-box usage would be as follows:

class Song < ActiveRecord::Base
  is_tokenable :label
end

The resulting attribute=value pairs would yield: {label: "Can't You Hear Me Knocking", token: "cant_you_hear_me_knocking"}.

Custom Token

If the default behavior is not to your liking then the ability to define a specific token attribute is possible. Example:

class Song < ActiveRecord::Base
  is_tokenable :label, token: :slug
end

The resulting attribute=value pairs would yield: {label: "Can't You Hear Me Knocking", slug: "cant_you_hear_me_knocking"}.

Uniqueness

By default, the ability to auto-generate unique tokens is disabled. However, should you want to ensure that unique tokens are always generated then the following is possible:

class Song < ActiveRecord::Base
  is_tokenable :label, token: :slug, unique: true
end

This means that if the "cant_you_hear_me_knocking" token already exists, a unique token will be generated by adding a datetime stamp suffix to the first generated token. Example: "cant_you_hear_me_knocking-20110115101045". It will keep iterating until a unique token is produced.

Validation

Token validation is performed prior to saving, using the same criteria as used to create the token.

Finders

The ability to search by token or ID is supported via the find_by_identifier class method. This means that Song.find_by_identifier("cant_you_hear_me_knocking") is just as valid as Song.find_by_identifier(1). The token is searched for first, otherwise defaulting to the original ID. Additionally, the default to_param instance method is overwritten so that if a token value exists, then the token is returned (otherwise the original ID is returned). For example, song.to_param could yield "cant_you_hear_me_knocking" or 1 depending on whether a token value was found or not. These can prove useful when building pretty URLs (example: /songs/cant_you_hear_me_knocking). That said, if the auto-computation of a token or ID for a model is not desired then set the find_with_token option to false. Example:

class Song < ActiveRecord::Base
  is_tokenable :label, find_with_token: false
end

Multiple Attributes

In case a single attribute is not enough for token generation, it is possible use multiple attributes. Example (where first_name = "Jimi" and last_name = "Hendrix"):

class Musician < ActiveRecord::Base
  is_tokenable [:first_name, :last_name]
end

The resulting token would be: jimi_hendrix. Attribute order is important, so the reverse is possible as well:

class Musician < ActiveRecord::Base
  is_tokenable [:last_name, :first_name]
end

In this case, the token value would be the reverse: "hendrix_jimi". The default delimiter can be overwritten too:

class Musician < ActiveRecord::Base
  is_tokenable [:first_name, :last_name], delimiter: '-'
end

...which would yield: "jimi-hendrix".

Scopes

Scopes allow token generation to be limited to single/multiple attributes. Example:

class Album < ActiveRecord::Base
  is_tokenable :title, scope: :genre_id
end

This would limit the token to be unique for with the same genre. Based on the definition above, the following would be valid:

  • title: "Houses of the Holy", token: "houses_of_the_holy", genre_id: 1
  • title: "Houses of the Holy", token: "houses_of_the_holy", genre_id: 2

However, it would be invalid if the genre ID was 1 for both records.

More than one scope is also available by passing in an array to the scope. Example:

class Album < ActiveRecord::Base
  is_tokenable :title, scope: [:genre_id, :category_id]
end

Based on the example above, the following would be valid:

  • title: "Houses of the Holy", token: "houses_of_the_holy", genre_id: 1, category_id: 1
  • title: "Houses of the Holy", token: "houses_of_the_holy", genre_id: 2, category_id: 1

Of course, using more than one of the same genre_id and category_id combinations would throw a validation error.

Class Methods

There is a convenience method for rebuilding/upgrading database records with token support. By default it will generate tokens for records with missing tokens. Example:

Song.rebuild_tokens

Pass the true to the method with force all tokens to be rebuilt whether they exist or not. Example:

Song.rebuild_tokens true

Kit

There is a utility kit that can be easily referenced with the following benefits:

  • Tokener::Kit.tokenize - The main method used to tokenize a string.
  • Tokener::Kit.detokenize - Reverses the work of tokenize (roughly) to turn a token back into human readable text.

Generators

For convenience, a Rails migration generator is available from the command line in case it is necessary to add token support to previously created tables.

Usage:

rails generate tokener:migrate table [column] [options]

Example:

rails generate tokener:migrate songs

This will then yield the following migration:

db/migrate/<datetime stamp>_add_token_to_songs.rb

Testing

To test, do the following:

  1. cd to the gem root.
  2. bundle install
  3. bundle exec rspec spec

Versioning

Read Semantic Versioning for details. Briefly, it means:

  • Patch (x.y.Z) - Incremented for small, backwards compatible bug fixes.
  • Minor (x.Y.z) - Incremented for new, backwards compatible public API enhancements and/or bug fixes.
  • Major (X.y.z) - Incremented for any backwards incompatible public API changes.

Contributions

Read CONTRIBUTING for details.

Credits

Developed by Brooke Kuhlmann at Red Alchemist

License

Copyright (c) 2010 Red Alchemist. Read the LICENSE for details.

History

Read the CHANGELOG for details. Built with Gemsmith.

Something went wrong with that request. Please try again.