Created
July 9, 2011 01:18
-
-
Save gavinhughes/1073179 to your computer and use it in GitHub Desktop.
Convert string to underscored slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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