Skip to content

Commit

Permalink
Add permalink history for taxon on friendly-id
Browse files Browse the repository at this point in the history
  • Loading branch information
shahmayur001 committed Feb 5, 2025
1 parent ca1ae4d commit c29f367
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
24 changes: 22 additions & 2 deletions core/app/models/spree/taxon.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

module Spree
class Taxon < Spree::Base
extend FriendlyId
friendly_id :permalink, use: :history, slug_column: :permalink

acts_as_nested_set dependent: :destroy

belongs_to :taxonomy, class_name: 'Spree::Taxonomy', inverse_of: :taxons
Expand All @@ -13,8 +16,7 @@ class Taxon < Spree::Base
has_many :promotion_rule_taxons
has_many :promotion_rules, through: :promotion_rule_taxons

before_create :set_permalink
before_update :set_permalink
before_save :set_permalink
after_update :update_child_permalinks, if: :saved_change_to_permalink?

validates :name, presence: true
Expand Down Expand Up @@ -121,6 +123,24 @@ def permalink_part=(value)
end
end

# override for {FriendlyId::Slugged#should_generate_new_friendly_id?} method,
# to control exactly when new friendly ids are set or updated
def should_generate_new_friendly_id?
permalink_changed? || super
end

# override for {FriendlyId::Slugged#normalize_friendly_id} method,
# to control over the slug format
def normalize_friendly_id(value)
return '' if value.blank?

parts = value.to_s.split('/')
last_word = parts.pop
corrected_last_word = Spree::Config.taxon_url_parametizer_class.parameterize(last_word)

(parts << corrected_last_word).join('/')
end

private

def touch_ancestors_and_taxonomy
Expand Down
21 changes: 21 additions & 0 deletions core/spec/models/spree/taxon_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,25 @@
end
end
end

context 'stores history of permalinks' do
let!(:parent_taxon) { create(:taxon, name: "brands") }
let!(:taxon) { create(:taxon, name: "ruby on rails", parent: parent_taxon) }

it 'should store the previous slug when permalink is updated' do
initial_permalink = taxon.permalink

expect(taxon.slugs.count).to eq(1)
expect(taxon.slugs.last.slug).to eq(initial_permalink)

taxon.update(permalink: "rails for ruby")
updated_permalink = taxon.permalink

expect(taxon.permalink).to eq(updated_permalink)
expect(taxon.slugs.count).to eq(2)

expect(taxon.slugs.pluck(:slug)).to include(initial_permalink)
expect(taxon.slugs.pluck(:slug)).to include(updated_permalink)
end
end
end

0 comments on commit c29f367

Please sign in to comment.