How to slugify a string in Ruby on Rails

How to slugify a string in Ruby on Rails

/ #Ruby on Rails


Slugifying a string in Ruby on Rails is very easy to do. Here's a few examples on how to do it.

1. Using Rails' parameterize method (I recommend this)

string = "Hello Stein! This is a Test"
slug = string.parameterize
# => "hello-stein-this-is-a-test"

# You can use custom separators
slug = string.parameterize(separator: '_')
# => "hello_stein_this_is_a_test"

2. Using parameterize with locale support

string = "Café & Restaurant"
slug = string.parameterize
# => "cafe-restaurant"

# Preserve unicode characters
slug = string.parameterize(preserve_case: true)
# => "Cafe-Restaurant"

3. For model attributes (Often used

class Article < ApplicationRecord
  validates :slug, presence: true, uniqueness: true
  before_validation :generate_slug, if: :title_changed?

  private

  def generate_slug
    self.slug = title.parameterize if title.present?
  end
end

4. Custom slugify method

Or if you want to make your own method to be more in control.

def slugify(string)
  string.downcase
        .strip
        .gsub(/[^\w\s-]/, '') # Remove non-word characters except spaces and hyphens
        .gsub(/\s+/, '-')     # Replace spaces with hyphens
        .gsub(/-+/, '-')      # Replace multiple hyphens with single hyphen
        .gsub(/^-|-$/, '')    # Remove leading/trailing hyphens
end

slug = slugify("Hello World! This is a Test")
# => "hello-world-this-is-a-test"

Summary

So, that was 4 different ways to make slugs from strings in Ruby on Rails. What's your preferred way to do this?

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.