Created
March 22, 2015 14:28
-
-
Save andersr/85643f1ae99a9e79bd7f to your computer and use it in GitHub Desktop.
Generate URL 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
before_save :generate_title_slug | |
protected | |
def generate_title_slug | |
title_slug = self.title.downcase.strip.truncate(50) | |
#replace spaces with dashes | |
title_slug.gsub! " ", "-" | |
#blow away apostrophes | |
title_slug.gsub! /['`]/,"" | |
# convert @ --> at, & --> and | |
title_slug.gsub! /\s*@\s*/, "at" | |
title_slug.gsub! /\s*&\s*/, "and" | |
#replace all non alphanumeric, underscore or periods with dashes | |
title_slug.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '-' | |
#convert double underscores, double dashes to single dash | |
title_slug.gsub! /_+|-+/,"-" | |
#strip off leading/trailing underscore | |
title_slug.gsub! /\A[_\.]+|[_\.]+\z/,"" | |
self[:title_slug] = title_slug | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment