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

前端 未结 12 844
北荒
北荒 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 19:06

    I use the following, which will

    • translate & --> "and" and @ --> "at"
    • doesn't insert an underscore in place of an apostrophe, so "foo's" --> "foos"
    • doesn't include double-underscores
    • doesn't create slug that begins or ends with an underscore
    
      def to_slug
        #strip the string
        ret = self.strip
    
        #blow away apostrophes
        ret.gsub! /['`]/,""
    
        # @ --> at, and & --> and
        ret.gsub! /\s*@\s*/, " at "
        ret.gsub! /\s*&\s*/, " and "
    
        #replace all non alphanumeric, underscore or periods with underscore
         ret.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '_'  
    
         #convert double underscores to single
         ret.gsub! /_+/,"_"
    
         #strip off leading/trailing underscore
         ret.gsub! /\A[_\.]+|[_\.]+\z/,""
    
         ret
      end
    

    so, for example:

    
    >> s = "mom & dad @home!"
    => "mom & dad @home!"
    >> s.to_slug
    > "mom_and_dad_at_home"
    

提交回复
热议问题