Created
May 9, 2012 16:22
-
-
Save bogdanconstantinescu/2646176 to your computer and use it in GitHub Desktop.
to_slug method for ActiveRecord model
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
# 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