TIL: Overriding Permalink Generation in FriendlyId

FriendlyId is a helpful Ruby gem that streamlines creating permalinks and slugs for Rails applications. In Pika we're using it to help with generating permalinks for blog posts and pages as well as slugs for tags. When a customer wrote in with a request to modify the behavior of these permalinks, I wasn’t sure how easy it would be to override the default behavior. Turns out it wasn’t too bad!

In our case we wanted to change the permalink generated for things titled or named with apostrophes. For example, if your blog post title was "What’s the frequency, Kenneth?", when FriendlyId created the permalink it would replace the apostrophe with a dash:

what-s-the-frequency-kenneth

We wanted to change that so the permalink simply removed the apostrophe:

whats-the-frequency-kenneth

In fact, we wanted to do the same for all sorts of apostrophe, quote, and double-quote characters. To make it happen we added this to our config/initializers/friendly_id.rb file:

module FriendlyId
module Slugged

alias_method :original_normalize_friendly_id, :normalize_friendly_id
def normalize_friendly_id(string)
original_normalize_friendly_id(string.gsub(/'|"|‘|’|“|”/, ""))
end

end
end

We added some tests to assure that the behavior continues to work as expected and called it a day. 👏