Need a Slug?

Ever needed a URL for a title of an article, event, etc. in your Rails app? Rails provides a free method for creating this type of slug: String#parameterize.

You can call the method, which downcases, hyphenates, transliterates, and removes punctuation as:

> "Need a Slug?".parameterize
=> "need-a-slug"

It’s great for creating URLs, but remember that it’s not unique, so two strings can return the same parameterized output and cause issues if it’s used naïvely:

> "Need a Slug?".parameterize
=> "need-a-slug"
> "Need a slug.".parameterize
=> "need-a-slug"

It’s also useful if you need to quickly grab a slug from a string outside a Rails app. I just used it to post an event with the parameterized path of the event’s title.

$ heroku run console
> "Title of my Meetup, which was pretty long".parameterize
=> "title-of-my-meetup-which-was-pretty-long"

Use it in good health.

Randy lay there like a slug! It was his only defense!

Ralphie as an Adult, narrating in A Christmas Story