Ruby post title to slug

RubyStringLowercaseGsub

Ruby Problem Overview


How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).

So basically:

  • downcase all letters
  • convert spaces to hyphens
  • delete extraneous characters

Ruby Solutions


Solution 1 - Ruby

Is this Rails? (works in Sinatra)

string.parameterize

That's it. For even more sophisticated slugging, see ActsAsUrl. It can do the following:

"rock & roll".to_url => "rock-and-roll"
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

Solution 2 - Ruby

slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')

downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).

Solution 3 - Ruby

to_slug is a great Rails plugin that handles pretty much everything, including funky characters, but its implementation is very simple. Chuck it onto String and you'll be sorted. Here's the source condensed down:

String.class_eval do
  def to_slug
    value = self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
    value.gsub!(/[']+/, '')
    value.gsub!(/\W+/, ' ')
    value.strip!
    value.downcase!
    value.gsub!(' ', '-')
    value
  end
end

Solution 4 - Ruby

I've used this gem.It's simple but helpful.

https://rubygems.org/gems/string_helpers

Solution 5 - Ruby

I like FriendlyId, the self-professed "Swiss Army Bulldozer" of creating slugs. https://github.com/norman/friendly_id

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionma11hew28View Question on Stackoverflow
Solution 1 - RubyMark ThomasView Answer on Stackoverflow
Solution 2 - RubyBen LeeView Answer on Stackoverflow
Solution 3 - RubyJamie RumbelowView Answer on Stackoverflow
Solution 4 - RubyDiego MontadoriView Answer on Stackoverflow
Solution 5 - RubyAaron SumnerView Answer on Stackoverflow