norman/friendly_id — pull request #290 by raymccoy (2012-05-26 02:23:16+00:00)
Title: Allow to try different slugging approaches in conflicts

This adds the overridable method `resolve_slug_conflict`, which will be called when there is a slug conflict before adding a sequence number.

It allows to try different names for the slug before relying on the sequence.

For example, you might want to add a country to the slug only if there is a conflict. If this still fails, you might want to add a city. If that fails then a sequence number will be appended on top of last attempt.

Usage:

class Person < ActiveRecord::Base
friendly_id :name

def resolve_slug_conflict(attempts)
case attempts
when 1
"#{name} from #{location}"
when 2
"#{name} from #{city} in #{location}"
else
super
end
end
end

bob1 = Person.create! :name => "Bob Smith", :country => "USA", :city => "New York City"
bob2 = Person.create! :name => "Bob Smith", :country => "USA", :city => "New York City"
bob3 = Person.create! :name => "Bob Smith", :country => "USA", :city => "New York City"
bob4 = Person.create! :name => "Bob Smith", :country => "USA", :city => "New York City"
bob1.friendly_id #=> "bob-smith"
bob2.friendly_id #=> "bob-smith-from-usa"
bob3.friendly_id #=> "bob-smith-from-new-york-city-in-usa"
bob4.friendly_id #=> "bob-smith-from-new-york-city-in-usa--2"