Heading image for post: Using Slugworth to your Benefit


Using Slugworth to your Benefit

Profile picture of Matt Polito

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 String called slug.

Now we'll include the library into our class:

class User < ActiveRecord::Base
  include Slugworth
  slugged_with :name

After you include the 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 name, or 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_slug is 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::RecordNotFound exception... if not found.
  • #to_param has been defined as a paramaterized version of the attribute declared to slugged_with.
  • Validations stating that slug is 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.

If you're in need of something that can handle more complex text translation or the handling of international text... take a look at FriendlyId and Stringex. They should have you covered.

For simple slugging solutions, Slugworth is your man!

More posts about Development Ruby