Automatic slug generation advanced with de-dupe technology

Language: Ruby

# I'm not sure if there's a better way to do this, but it works...

# The tests look like:

  test "deals with dupe slugs automatically" do
    v1 = Video.make(:name => "Nick Vegas")
    v2 = Video.make(:name => "Nick Vegas")
    v3 = Video.make(:name => "Nick Vegas")
    assert_equal "nickvegas", v1.slug
    assert_equal "nickvegas2", v2.slug
    assert_equal "nickvegas3", v3.slug
  end

# The model and relevant code looks like:

class Video < ActiveRecord::Base
  before_validation :generate_slug
  validates_presence_of :slug
  validates_uniqueness_of :slug
  
  def generate_slug
    slug = name.parameterize.gsub('-', '')
    if Video.find_by_slug(slug)
      counter = 2
      until Video.find_by_slug("#{slug}#{counter}").nil?
        counter += 1
      end
      slug = "#{slug}#{counter}"
    end
    self.slug = slug
  rescue
    # use validations to catch errors
  end   
end
Reveal More
Added almost 2 years ago by Costco_normal trevorturk