Created
February 17, 2015 13:46
-
-
Save jheg/951a0444c98694203b41 to your computer and use it in GitHub Desktop.
slugging
This file contains 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
def make_slug(post_title) | |
the_slug = post_title.gsub(/[\W_]/, '-').squeeze.chop.downcase | |
return the_slug | |
end | |
def ensure_slug_not_duplicate | |
the_slug = make_slug(self.title) | |
post = Post.find_by(slug: the_slug) | |
counter = 2 | |
while post && post != self | |
the_slug = append_suffix(the_slug, counter) | |
post = Post.find_by(slug: the_slug) | |
counter += 1 | |
end | |
self.slug = the_slug | |
end | |
def append_suffix(str,counter) | |
if str.split('-').last.to_i != 0 | |
return str.split('-').slice(0...-1).join('-') + "-#{counter}" | |
else | |
str = str + "-#{counter}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment