Skip to content

Instantly share code, notes, and snippets.

@jheg
Created February 17, 2015 13:46
Show Gist options
  • Save jheg/951a0444c98694203b41 to your computer and use it in GitHub Desktop.
Save jheg/951a0444c98694203b41 to your computer and use it in GitHub Desktop.
slugging
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