Skip to content

Instantly share code, notes, and snippets.

@jheg
Created February 17, 2015 15:19
Show Gist options
  • Save jheg/3ee11ef78e91ffb7e2e9 to your computer and use it in GitHub Desktop.
Save jheg/3ee11ef78e91ffb7e2e9 to your computer and use it in GitHub Desktop.
losing a trailing '-' if present
def generate_slug
the_slug = to_slug(self.title)
post = Post.find_by(slug: the_slug)
count = 2
while post && post != self
the_slug = append_suffix(the_slug, count)
post = Post.find_by(slug: the_slug)
count += 1
end
self.slug = the_slug.downcase
end
def append_suffix(str,count)
if str.split('-').last.to_i != 0
return str.split('-').slice(0...-1).join('-') + "-#{count}"
else
return str + "-#{count}"
end
end
def to_slug(name)
str = name.strip
str.gsub!(/\s*[^A-Za-z0-9]\s*/, '-')
str.gsub!(/-+/,"-")
if str.last == '-'
str.chop!
end
str.downcase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment