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

前端 未结 12 867
北荒
北荒 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:45

    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
    

提交回复
热议问题