Skip to content

Instantly share code, notes, and snippets.

@bogdanconstantinescu
Created May 9, 2012 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdanconstantinescu/2646176 to your computer and use it in GitHub Desktop.
Save bogdanconstantinescu/2646176 to your computer and use it in GitHub Desktop.
to_slug method for ActiveRecord model
# Hook this up in your ActiveRecord model for a nicer slug
# I use it on before_save :to_slug
def to_slug
# Translate usual characters encountered
convert_map = {
/\@/ => ' at ',
/\&/ => ' and ',
/\%/ => ' percent ',
}
convert_map.each do |pattern, replacement|
self.slug = slug.gsub(pattern, replacement)
end
self.slug = slug.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/[-]{2,}/, '-').gsub(/^-/, '').gsub(/-$/, '')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment