Handler

Handler is currently compatible with Rails 3.x, 4.x, and 5.x.

Handler is a Rails plugin that generates handles (filesystem- and URL-friendly names) for ActiveRecord models based on a given attribute or method. For example, in your model:

handle_based_on :title

creates a generate_handle method which returns a lowercase ASCII version of the title attribute, for example:

"Häagen Dazs"             --> "haagen_dazs"
".38 Special"             --> "38_special"
"Guns N' Roses"           --> "guns_n_roses"
"Emerson, Lake & Palmer"  --> "emerson_lake_and_palmer"

By default the word separator is “_” but you can change this with the :separator option, for example:

handle_based_on :title, :separator => "-"

Transliteration using reasonable ASCII approximations of non-ASCII characters is attempted, using the excellent unidecode gem (rubyforge.org/projects/unidecode) if it’s available (recommended: sudo gem install unidecode).

Usually you want handles to be unique but if they’re generated automatically you can’t very well use ActiveRecord validation. Instead Handler will append numbers (starting with 2) to duplicate handles, so if you already have a Person with handle george_brett, a new Person with name “George Brett” will receive the handle george_brett_2. To disable this feature (and allow duplicate handles):

handle_based_on :name, :unique => false

Handler doesn’t store handles automatically, but provides a private method assign_handle you can call to do so. Intended use is something like this:

before_save :assign_handle

By default the handle is written to the handle attribute but you can change this like so:

handle_based_on :name, :write_to => :alias

The above will store the handle as the alias attribute.

Copyright © 2009 Alex Reisner, released under the MIT license