Though concerns have been around since Rails 3.2, they were extracted as a separate feature in Rails 4. At low-level, concerns are basically ruby modules that can be mixed with model or controller classes to make the defined methods available to that class in its context.
Slugs are an important feature in today’s apps where URLs play an important role for several reason. Search Engine Optimization, better user experience, easier bookmarking. There are gems available for creating slugs, like fiendly_id and mongoid-slug. However, a lot of times we need a custom solution. In rails it is easy enough to roll out our own.
We will first create a file for concern inside models.
We will call this concern inside our model :
Now, this uses the default to_param method of Rails. Also, the url generated in this case for a title like, “this is a test”, will look like the following :
For SEO reasons, and for the reasons of localization, a lot of times URLs might have a UID.
In order to generate uid, we will generate a random number and append it to the title. Also we will tie it to the callback in order to generate it before the record is created.
A couple of things now remain. First, we need a field called title in order to create the slug. What if the model does not have such a field. In mongoid, we can assign a document field a different name. So a field called name, can also be alternatively called as slug.
Likewise, we will have to change our slug method to suit this change :
Lastly, we need to sanitize the string in our title. We will look for white spaces and place dashes instead of them, remove special characters from the string, remove entities.
The resultant URL is something like the following: