Slug generation in rails
Sep.01, 2008 in
Ruby on Rails
Just recently I made a very minor update to my slugify method I use in rails (which I add to String via a monkey-patch).
It’s pretty much like your stock-standard slugification method, this one produces a URL-friendly slug containing only letters and numbers, dashes seperate elements in the string and a few other nice things (single quotation marks are just stripped and not made spaces, and ‘&’ is replaced with ‘and’).
self.downcase.gsub(/&/, ' and ').gsub(/[^a-z0-9']+/, '-').gsub(/^-|-$|'/, '')
end
end

September 1st, 2008 at 1:38 pm
Code has been revised thanks to a fault pointed out by Sam Pohlenz (sampohlenz.com)
September 1st, 2008 at 2:06 pm
Specs and a javascript version available at http://gist.github.com/8264.
September 11th, 2008 at 2:36 am
Looks like something similar is making its way into Edge rails: http://github.com/rails/rails/commit/b8e8be83e952163e225f9b38bd7251cba9c44f38.
October 2nd, 2008 at 4:57 pm
One more sugestion
class String
def slugify(separator = ‘_’)
self.downcase.gsub(/\&+/, ‘ and ‘).gsub(/\W+/, ‘ ‘).split.join(separator)
end
end
October 3rd, 2008 at 3:20 pm
Looks like custom slugifiers are about to be the thing of the past with a really nice slugifier being integrated into rails core, based off of http://github.com/henrik/slugalizer. Looks great!