Commit 4004a064b440aae7dffca0a7444641d75f609c4b
1 parent
1260d03e
Exists in
staging
and in
42 other branches
ActionItem70: recalculating paths
git-svn-id: https://svn.colivre.coop.br/svn/noosfero/trunk@526 3f533792-8f58-4932-b0fe-aaf55b0a4547
Showing
2 changed files
with
35 additions
and
0 deletions
Show diff stats
app/models/category.rb
| ... | ... | @@ -23,7 +23,14 @@ class Category < ActiveRecord::Base |
| 23 | 23 | self.find(:all, :conditions => ['parent_id is null and environment_id = ?', environment.id ]) |
| 24 | 24 | end |
| 25 | 25 | |
| 26 | + # used to know when to trigger batch renaming | |
| 27 | + attr_accessor :recalculate_path | |
| 28 | + | |
| 26 | 29 | def name=(value) |
| 30 | + if self.name != value | |
| 31 | + self.recalculate_path = true | |
| 32 | + end | |
| 33 | + | |
| 27 | 34 | self[:name] = value |
| 28 | 35 | unless self.name.blank? |
| 29 | 36 | 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 |
| 46 | 53 | end |
| 47 | 54 | end |
| 48 | 55 | |
| 56 | + # calculate the right path | |
| 49 | 57 | before_create do |cat| |
| 50 | 58 | if cat.path == cat.slug && (! cat.top_level?) |
| 51 | 59 | cat.path = cat.calculate_path |
| 52 | 60 | end |
| 53 | 61 | end |
| 54 | 62 | |
| 63 | + # when renaming a category, all children categories must have their paths | |
| 64 | + # recalculated | |
| 65 | + after_update do |cat| | |
| 66 | + if cat.recalculate_path | |
| 67 | + cat.children.each do |item| | |
| 68 | + item.path = item.calculate_path | |
| 69 | + item.recalculate_path = true | |
| 70 | + item.save! | |
| 71 | + end | |
| 72 | + end | |
| 73 | + cat.recalculate_path = false | |
| 74 | + end | |
| 75 | + | |
| 55 | 76 | end | ... | ... |
test/unit/category_test.rb
| ... | ... | @@ -137,4 +137,18 @@ class CategoryTest < Test::Unit::TestCase |
| 137 | 137 | |
| 138 | 138 | end |
| 139 | 139 | |
| 140 | + def test_renaming_a_category_should_change_path_of_children | |
| 141 | + c1 = Category.create!(:name => 'parent', :environment_id => @env.id) | |
| 142 | + c2 = Category.create!(:name => 'child', :environment_id => @env.id, :parent_id => c1.id) | |
| 143 | + c3 = Category.create!(:name => 'grandchild', :environment_id => @env.id, :parent_id => c2.id) | |
| 144 | + | |
| 145 | + c1.name = 'parent new name' | |
| 146 | + c1.save! | |
| 147 | + | |
| 148 | + assert_equal 'parent-new-name', c1.path | |
| 149 | + assert_equal 'parent-new-name/child', Category.find(c2.id).path | |
| 150 | + assert_equal 'parent-new-name/child/grandchild', Category.find(c3.id).path | |
| 151 | + | |
| 152 | + end | |
| 153 | + | |
| 140 | 154 | end | ... | ... |