Created
February 17, 2015 15:19
-
-
Save jheg/3ee11ef78e91ffb7e2e9 to your computer and use it in GitHub Desktop.
losing a trailing '-' if present
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 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