Created
October 9, 2011 23:34
-
-
Save victorbstan/1274366 to your computer and use it in GitHub Desktop.
A Rails model example for generating slugs for a "slug" parameter/column
This file contains 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
before_validation :slug_to_slug | |
protected | |
def slug_to_slug | |
self.slug = self.to_slug | |
end | |
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 underscores to single | |
ret.gsub! /-+/, "-" | |
# strip off leading/trailing dash | |
ret.gsub! /\A[-\.]+|[-\.]+\z/, "" | |
ret | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment