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

前端 未结 12 841
北荒
北荒 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条回答
  •  Happy的楠姐
    2020-11-30 19:04

    I found the Unidecode gem to be much too heavyweight, loading nearly 200 YAML files, for what I needed. I knew iconv had some support for the basic translations, and while it isn't perfect, it's built in and fairly lightweight. This is what I came up with:

    require 'iconv' # unless you're in Rails or already have it loaded
    def slugify(text)
      text.downcase!
      text = Iconv.conv('ASCII//TRANSLIT//IGNORE', 'UTF8', text)
    
      # Replace whitespace characters with hyphens, avoiding duplication
      text.gsub! /\s+/, '-'
    
      # Remove anything that isn't alphanumeric or a hyphen
      text.gsub! /[^a-z0-9-]+/, ''
    
      # Chomp trailing hyphens
      text.chomp '-'
    end
    

    Obviously you should probably add it as an instance method on any objects you'll be running it on, but for clarity, I didn't.

提交回复
热议问题