Commit e2a2033228c615b47c01ef18644704c5d65175d5
1 parent
0da926a2
Exists in
master
and in
28 other branches
ActionItem23: adding traversal method to acts_as_filesystem
git-svn-id: https://svn.colivre.coop.br/svn/noosfero/trunk@1120 3f533792-8f58-4932-b0fe-aaf55b0a4547
Showing
2 changed files
with
44 additions
and
0 deletions
Show diff stats
lib/acts_as_filesystem.rb
| ... | ... | @@ -150,6 +150,21 @@ module ActsAsFileSystem |
| 150 | 150 | @hierarchy |
| 151 | 151 | end |
| 152 | 152 | |
| 153 | + def map_traversal(&block) | |
| 154 | + stack = [] | |
| 155 | + result = [] | |
| 156 | + stack.push(self) | |
| 157 | + while !stack.empty? | |
| 158 | + element = stack.pop | |
| 159 | + result.push(element) | |
| 160 | + element.children.each do |item| | |
| 161 | + stack.push(item) | |
| 162 | + end | |
| 163 | + end | |
| 164 | + block ||= (lambda { |x| x }) | |
| 165 | + result.map(&block) | |
| 166 | + end | |
| 167 | + | |
| 153 | 168 | end |
| 154 | 169 | end |
| 155 | 170 | ... | ... |
test/unit/acts_as_filesystem_test.rb
| ... | ... | @@ -21,4 +21,33 @@ class ActsAsFilesystemTest < Test::Unit::TestCase |
| 21 | 21 | assert_not_same list, a.hierarchy(true) |
| 22 | 22 | end |
| 23 | 23 | |
| 24 | + should 'list the full tree' do | |
| 25 | + profile = create_user('testinguser').person | |
| 26 | + | |
| 27 | + a1 = profile.articles.build(:name => 'a1'); a1.save! | |
| 28 | + | |
| 29 | + a1_1 = profile.articles.build(:name => 'a1.1'); a1_1.parent = a1; a1_1.save! | |
| 30 | + a1_2 = profile.articles.build(:name => 'a1.2'); a1_2.parent = a1; a1_2.save! | |
| 31 | + | |
| 32 | + a1_1_1 = profile.articles.build(:name => 'a1.1.1'); a1_1_1.parent = a1_1; a1_1_1.save! | |
| 33 | + a1_1_2 = profile.articles.build(:name => 'a1.1.2'); a1_1_2.parent = a1_1; a1_1_2.save! | |
| 34 | + | |
| 35 | + assert_equivalent [a1, a1_1, a1_2, a1_1_1, a1_1_2], a1.map_traversal | |
| 36 | + end | |
| 37 | + | |
| 38 | + should 'be able to traverse with a block' do | |
| 39 | + profile = create_user('testinguser').person | |
| 40 | + | |
| 41 | + a1 = profile.articles.build(:name => 'a1'); a1.save! | |
| 42 | + | |
| 43 | + a1_1 = profile.articles.build(:name => 'a1.1'); a1_1.parent = a1; a1_1.save! | |
| 44 | + a1_2 = profile.articles.build(:name => 'a1.2'); a1_2.parent = a1; a1_2.save! | |
| 45 | + | |
| 46 | + a1_1_1 = profile.articles.build(:name => 'a1.1.1'); a1_1_1.parent = a1_1; a1_1_1.save! | |
| 47 | + a1_1_2 = profile.articles.build(:name => 'a1.1.2'); a1_1_2.parent = a1_1; a1_1_2.save! | |
| 48 | + | |
| 49 | + assert_equivalent ['a1', 'a1.1', 'a1.2', 'a1.1.1', 'a1.1.2'], a1.map_traversal { |item| item.name } | |
| 50 | + | |
| 51 | + end | |
| 52 | + | |
| 24 | 53 | end | ... | ... |