Skip to content

Instantly share code, notes, and snippets.

@CodeZombie
Created April 3, 2015 00:50
Show Gist options
  • Save CodeZombie/533edc6d7708151ecc61 to your computer and use it in GitHub Desktop.
Save CodeZombie/533edc6d7708151ecc61 to your computer and use it in GitHub Desktop.
Ruby Slug Generator
def createSlug(title)
maxlength = 35
title = title.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase
return title[0, title.length > maxlength ? (title[0, maxlength].rindex('-') or maxlength) : maxlength]
end
@CodeZombie
Copy link
Author

This is a little slug generator for ruby.

features
1 removes all non alphanumeric and dash characters
2 removes any repeating dashes
3 strips special characters, but does so in a way that slugs will always be maxlength if they can be

@kont-noor
Copy link

it's enough return title[0, maxlength]
the sample:

2.4.1 :012 > "qwertyuiopasdfghjkl"[0,10]
# => "qwertyuiop"
2.4.1 :013 > "qwertyuiopasdfghjkl"[0,100]
# => "qwertyuiopasdfghjkl"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment