Skip to content

Instantly share code, notes, and snippets.

@gavinhughes
Created July 9, 2011 01:18
Show Gist options
  • Save gavinhughes/1073179 to your computer and use it in GitHub Desktop.
Save gavinhughes/1073179 to your computer and use it in GitHub Desktop.
Convert string to underscored slug
module Slugify
def slugify(string)
# Strip the string
ret = string.strip
# Blow away apostrophes
ret.gsub! /['`]/,""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# Replace all non-alphanumeric or periods with underscore
ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '_'
# Replace hyphens with underscore
ret.gsub! /\-/, "_"
# Convert double underscores to single
ret.gsub! /_+/,"_"
# Strip off leading/trailing underscore
ret.gsub! /\A[_\.]+|[_\.]+\z/,""
ret
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment