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

前端 未结 12 820
北荒
北荒 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条回答
  •  -上瘾入骨i
    2020-11-30 18:54

    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.

提交回复
热议问题