ruby-on-railsslug

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


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 nice for handling duplicate slugs, etc. Here are some popular Github plugins -- does anyone have any experience with them?

  1. http://github.com/rsl/stringex/tree/master
  2. http://github.com/norman/friendly_id/tree/master

Basically it seems like slugs are a totally solved problem, and I don't to reinvent the wheel.


Solution

  • I use the following, which will

    
      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"