Skip to content

Instantly share code, notes, and snippets.

@victorbstan
Created October 9, 2011 23:34
Show Gist options
  • Save victorbstan/1274366 to your computer and use it in GitHub Desktop.
Save victorbstan/1274366 to your computer and use it in GitHub Desktop.
A Rails model example for generating slugs for a "slug" parameter/column
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