From 43caf4bf4eb9a6da9790b8e37f87d658477a080b Mon Sep 17 00:00:00 2001 From: Tekin Suleyman Date: Thu, 14 May 2015 16:42:02 +0100 Subject: [PATCH] Fix bug in sequencing slugs starting with numbers Fixes a bug where a slug conflicting with a slug that starts with a number would get incorrectly sequenced based on the number at the start of the slug, rather than as a fresh sequence. --- lib/friendly_id/sequentially_slugged.rb | 10 ++++------ test/sequentially_slugged_test.rb | 9 +++++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/friendly_id/sequentially_slugged.rb b/lib/friendly_id/sequentially_slugged.rb index 3a23b0459..f742eeb83 100644 --- a/lib/friendly_id/sequentially_slugged.rb +++ b/lib/friendly_id/sequentially_slugged.rb @@ -32,15 +32,13 @@ def next_slug private def next_sequence_number - if last_sequence_number == 0 - 2 - else - last_sequence_number + 1 - end + last_sequence_number ? last_sequence_number + 1 : 2 end def last_sequence_number - slug_conflicts.last.split("#{slug}#{sequence_separator}").last.to_i + if match = /#{slug}#{sequence_separator}(\d+)/.match(slug_conflicts.last) + match[1].to_i + end end def slug_conflicts diff --git a/test/sequentially_slugged_test.rb b/test/sequentially_slugged_test.rb index 506421476..26621dbf1 100644 --- a/test/sequentially_slugged_test.rb +++ b/test/sequentially_slugged_test.rb @@ -64,6 +64,15 @@ def model_class end end + test "should correctly sequence slugs that begin with a number" do + transaction do + record1 = model_class.create! :name => "2010 to 2015 Records" + assert_equal "2010-to-2015-records", record1.slug + record2 = model_class.create! :name => "2010 to 2015 Records" + assert_equal "2010-to-2015-records-2", record2.slug + end + end + test "should sequence with a custom sequence separator" do model_class = Class.new(ActiveRecord::Base) do self.table_name = "novelists"