From 4004a064b440aae7dffca0a7444641d75f609c4b Mon Sep 17 00:00:00 2001 From: AntonioTerceiro Date: Mon, 24 Sep 2007 18:55:43 +0000 Subject: [PATCH] ActionItem70: recalculating paths --- app/models/category.rb | 21 +++++++++++++++++++++ test/unit/category_test.rb | 14 ++++++++++++++ 2 files changed, 35 insertions(+), 0 deletions(-) diff --git a/app/models/category.rb b/app/models/category.rb index c6691c2..970dab5 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -23,7 +23,14 @@ class Category < ActiveRecord::Base self.find(:all, :conditions => ['parent_id is null and environment_id = ?', environment.id ]) end + # used to know when to trigger batch renaming + attr_accessor :recalculate_path + def name=(value) + if self.name != value + self.recalculate_path = true + end + self[:name] = value unless self.name.blank? self.slug = self.name.transliterate.downcase.gsub( /[^-a-z0-9~\s\.:;+=_]/, '').gsub(/[\s\.:;=_+]+/, '-').gsub(/[\-]{2,}/, '-').to_s @@ -46,10 +53,24 @@ class Category < ActiveRecord::Base end end + # calculate the right path before_create do |cat| if cat.path == cat.slug && (! cat.top_level?) cat.path = cat.calculate_path end end + # when renaming a category, all children categories must have their paths + # recalculated + after_update do |cat| + if cat.recalculate_path + cat.children.each do |item| + item.path = item.calculate_path + item.recalculate_path = true + item.save! + end + end + cat.recalculate_path = false + end + end diff --git a/test/unit/category_test.rb b/test/unit/category_test.rb index e2a8c02..5502bc9 100644 --- a/test/unit/category_test.rb +++ b/test/unit/category_test.rb @@ -137,4 +137,18 @@ class CategoryTest < Test::Unit::TestCase end + def test_renaming_a_category_should_change_path_of_children + c1 = Category.create!(:name => 'parent', :environment_id => @env.id) + c2 = Category.create!(:name => 'child', :environment_id => @env.id, :parent_id => c1.id) + c3 = Category.create!(:name => 'grandchild', :environment_id => @env.id, :parent_id => c2.id) + + c1.name = 'parent new name' + c1.save! + + assert_equal 'parent-new-name', c1.path + assert_equal 'parent-new-name/child', Category.find(c2.id).path + assert_equal 'parent-new-name/child/grandchild', Category.find(c3.id).path + + end + end -- libgit2 0.21.2