Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby post title to slug

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
like image 519
ma11hew28 Avatar asked Nov 29 '10 21:11

ma11hew28


1 Answers

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" 
like image 123
Mark Thomas Avatar answered Sep 18 '22 00:09

Mark Thomas