Best way to generate slugs (human-readable IDs) in Rails

前端 未结 12 829
北荒
北荒 2020-11-30 18:05

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

12条回答
  •  独厮守ぢ
    2020-11-30 18:56

    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.

提交回复
热议问题