views:

2027

answers:

4

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 nice for handling duplicate slugs, etc. Here are some popular Github plugins -- does anyone have any experience with them?

  1. http://github.com/rsl/stringex/tree/master
  2. http://github.com/norman/friendly%5Fid/tree/master

Basically it seems like slugs are a totally solved problem, and I don't to reinvent the wheel.

+1  A: 

We use to_slug http://github.com/ludo/to_slug/tree/master. Does everything we need it to do (escaping 'funky characters'). Hope this helps.

EDIT: Seems to be breaking my link, sorry about that.

theIV
+1  A: 

Here is what I use:

class User < ActiveRecord::Base
  before_create :make_slug
  private

  def make_slug
    self.slug = self.name.downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')
  end
end

Pretty self explanatory, although the only problem with this is if there is already the same one, it won't be name-01 or something like that.

Example:

".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')

Outputs: -downcase-gsub-a-z1-9-chomp

Garrett
I didn't know about the parameterize inflection, I guess you could use that.
Garrett
+3  A: 
klochner
but I find the result dissatisfying. For my example above, you would get mom-dad-home. I like to try preserving symbol meanings.
klochner
good point.......
Horace Loeb
According to Google, dashes are better than underscores: http://www.google.com/support/webmasters/bin/answer.py?answer=76329`Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.`
Rei Miyasaka
Interesting, they recommend hyphens but don't say why.
klochner
+4  A: 

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.

Paweł Gościcki
I think even better is the stringex gem http://github.com/rsl/stringex/tree/master because it uses this inside of it and also adds other usefull things.
Rytis Lukoševičius
Do you really want to convert everything to ascii? Aren't unicode urls better for SEO?
Paul McMahon
I'm not entirely convinced about the uniode urls. I'm not sure the time has come for them. Yet. Although many disagree.
Paweł Gościcki