Skip to content

Instantly share code, notes, and snippets.

@andersr
Created March 22, 2015 14:28
Show Gist options
  • Save andersr/85643f1ae99a9e79bd7f to your computer and use it in GitHub Desktop.
Save andersr/85643f1ae99a9e79bd7f to your computer and use it in GitHub Desktop.
Generate URL slug
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