noizZze

Friendly Composite Keys in Mongoid

By default, Mongoid generates long hash-like keys from BSON that incorporate time, machine ID and counter. Pretty unique, but user unfriendly (for example, 47cc67093475061e3d95369d).

To solve this, Mongoid lets you define a custom composite key on the document and during the creation of the key it escapes special characters that may be found in the original string. So for example, ‘~’ is converted to ‘-tilda-’ and ‘-’ is converted to ‘-dash-‘. Yes, I don’t like it as well as I don’t like ‘_’ to be converted to ‘-undscr-‘. It looks pretty ugly in the URL.

So here’s a little trick if you want to make it replace all non-alpha and non-digit characters with dashes:

You need to put it in the initializer. I do this in config/initializers/mongoid.rb.