You know, like myblog.com/posts/donald-e-knuth.
Should I do this with the built in parameterize method?
What about a plugin? I could imagine a plugin being n
I modified it a bit to create dashes instead of underscores, if anyone is interested:
def to_slug(param=self.slug)
# strip the string
ret = param.strip
#blow away apostrophes
ret.gsub! /['`]/, ""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# replace all non alphanumeric, periods with dash
ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'
# replace underscore with dash
ret.gsub! /[-_]{2,}/, '-'
# convert double dashes to single
ret.gsub! /-+/, "-"
# strip off leading/trailing dash
ret.gsub! /\A[-\.]+|[-\.]+\z/, ""
ret
end
In Rails you can use #parameterize
For example:
> "Foo bar`s".parameterize
=> "foo-bar-s"
The main issue for my apps has been the apostrophes - rarely do you want the -s sitting out there on it's own.
class String
def to_slug
self.gsub(/['`]/, "").parameterize
end
end
Recently I had the same dilemma.
Since, like you, I don't want to reinvent the wheel, I chose friendly_id following the comparison on The Ruby Toolbox: Rails Permalinks & Slugs.
I based my decision on:
Hope this helps in taking the decision.
With Rails 3, I've created an initializer, slug.rb, in which I've put the following code:
class String
def to_slug
ActiveSupport::Inflector.transliterate(self.downcase).gsub(/[^a-zA-Z0-9]+/, '-').gsub(/-{2,}/, '-').gsub(/^-|-$/, '')
end
end
Then I use it anywhere I want in the code, it is defined for any string.
The transliterate transforms things like é,á,ô into e,a,o. As I am developing a site in portuguese, that matters.
The best way to generate slugs is to use the Unidecode gem. It has by far the largest transliteration database available. It has even transliterations for Chinese characters. Not to mention covering all European languages (including local dialects). It guarantees a bulletproof slug creation.
For example, consider those:
"Iñtërnâtiônàlizætiøn".to_slug
=> "internationalizaetion"
>> "中文測試".to_slug
=> "zhong-wen-ce-shi"
I use it in my version of the String.to_slug method in my ruby_extensions plugin. See ruby_extensions.rb for the to_slug method.