Using Slugworth to your Benefit
I love extracting small tools from everyday work. The more I can reuse something that is already written, the happier I am. While working on the new Hashrocket site I noticed something odd. There are many pages that make use of 'slugs' however their implementations varied slightly. Not because there was different functionality but due to different developers working on the project from time to time. To me this was unacceptable! At the very least it needed to be cleaned up and all slug functionality should be the same.
Now I am well aware of other slugging libraries and FriendlyId is an excellent library but it includes a lot of functionality that I didn't need. I wanted a straightforward and simple implementation that could be thrown into any of our projects (or anyone elses).
With those criteria in mind, Slugworth was born from this extraction.
Getting started is easy! Just ensure that your
ActiveRecord model has a database column of type
Now we'll include the library into our class:
class User < ActiveRecord::Base include Slugworth slugged_with :name end
Slugworth module, all you need to do is declare what method will be used to create the slug. The method passed to
slugged_with will then be parameterized. The most basic implementation would be to use something already available on your record like
title, but any method could be used to construct the text of the slug.
This provides most of the default slug functionality you would need.
- A finder
.find_by_slugis provided. This will, of course, do what you expect and find a single record by the slug attribute provided. However, it will throw an
ActiveRecord::RecordNotFoundexception... if not found.
#to_paramhas been defined as a paramaterized version of the attribute declared to
- Validations stating that
slugis present and unique in the database.
So far, my needs in regards to slugging have been very straightforward so my implementation has been able to stay very simple. Take a look at the source, there is not much there.
For simple slugging solutions, Slugworth is your man!