Commit 1b4b5b9ef43d960835d1d4077d965095eadf473c
1 parent
4370374c
Exists in
master
and in
29 other branches
ActionItem21: listing hierarchy of filesystem-like items
git-svn-id: https://svn.colivre.coop.br/svn/noosfero/trunk@952 3f533792-8f58-4932-b0fe-aaf55b0a4547
Showing
2 changed files
with
49 additions
and
0 deletions
Show diff stats
lib/acts_as_filesystem.rb
@@ -126,6 +126,31 @@ module ActsAsFileSystem | @@ -126,6 +126,31 @@ module ActsAsFileSystem | ||
126 | def explode_path | 126 | def explode_path |
127 | path.split(/\//) | 127 | path.split(/\//) |
128 | end | 128 | end |
129 | + | ||
130 | + # returns the full hierarchy from the top-level item to this one. For | ||
131 | + # example, if item1 has a children item2 and item2 has a children item3, | ||
132 | + # then item3's hierarchy would be [item1, item2, item3]. | ||
133 | + # | ||
134 | + # If +reload+ is passed as +true+, then the hierarchy is reload (usefull | ||
135 | + # when the ActiveRecord object was modified in some way, or just after | ||
136 | + # changing parent) | ||
137 | + def hierarchy(reload = false) | ||
138 | + if reload | ||
139 | + @hierarchy = nil | ||
140 | + end | ||
141 | + | ||
142 | + unless @hierarchy | ||
143 | + @hierarchy = [] | ||
144 | + item = self | ||
145 | + while item | ||
146 | + @hierarchy.unshift(item) | ||
147 | + item = item.parent | ||
148 | + end | ||
149 | + end | ||
150 | + | ||
151 | + @hierarchy | ||
152 | + end | ||
153 | + | ||
129 | end | 154 | end |
130 | end | 155 | end |
131 | 156 |
@@ -0,0 +1,24 @@ | @@ -0,0 +1,24 @@ | ||
1 | +require File.dirname(__FILE__) + '/../test_helper' | ||
2 | + | ||
3 | +class ActsAsFilesystemTest < Test::Unit::TestCase | ||
4 | + | ||
5 | + # FIXME shouldn't we test with a non-real model, instead of Article? | ||
6 | + | ||
7 | + should 'provide a hierarchy list' do | ||
8 | + profile = create_user('testinguser').person | ||
9 | + | ||
10 | + a1 = profile.articles.build(:name => 'a1'); a1.save! | ||
11 | + a2 = profile.articles.build(:name => 'a2'); a2.parent = a1; a2.save! | ||
12 | + a3 = profile.articles.build(:name => 'a3'); a3.parent = a2; a3.save! | ||
13 | + | ||
14 | + assert_equal [a1, a2, a3], a3.hierarchy | ||
15 | + end | ||
16 | + | ||
17 | + should 'be able to optionally reload the hierarchy' do | ||
18 | + a = Article.new | ||
19 | + list = a.hierarchy | ||
20 | + assert_same list, a.hierarchy | ||
21 | + assert_not_same list, a.hierarchy(true) | ||
22 | + end | ||
23 | + | ||
24 | +end |