diff --git a/lib/acts_as_filesystem.rb b/lib/acts_as_filesystem.rb index 4016337..9b98a2a 100644 --- a/lib/acts_as_filesystem.rb +++ b/lib/acts_as_filesystem.rb @@ -126,6 +126,31 @@ module ActsAsFileSystem def explode_path path.split(/\//) end + + # returns the full hierarchy from the top-level item to this one. For + # example, if item1 has a children item2 and item2 has a children item3, + # then item3's hierarchy would be [item1, item2, item3]. + # + # If +reload+ is passed as +true+, then the hierarchy is reload (usefull + # when the ActiveRecord object was modified in some way, or just after + # changing parent) + def hierarchy(reload = false) + if reload + @hierarchy = nil + end + + unless @hierarchy + @hierarchy = [] + item = self + while item + @hierarchy.unshift(item) + item = item.parent + end + end + + @hierarchy + end + end end diff --git a/test/unit/acts_as_filesystem_test.rb b/test/unit/acts_as_filesystem_test.rb new file mode 100644 index 0000000..e9da8dc --- /dev/null +++ b/test/unit/acts_as_filesystem_test.rb @@ -0,0 +1,24 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class ActsAsFilesystemTest < Test::Unit::TestCase + + # FIXME shouldn't we test with a non-real model, instead of Article? + + should 'provide a hierarchy list' do + profile = create_user('testinguser').person + + a1 = profile.articles.build(:name => 'a1'); a1.save! + a2 = profile.articles.build(:name => 'a2'); a2.parent = a1; a2.save! + a3 = profile.articles.build(:name => 'a3'); a3.parent = a2; a3.save! + + assert_equal [a1, a2, a3], a3.hierarchy + end + + should 'be able to optionally reload the hierarchy' do + a = Article.new + list = a.hierarchy + assert_same list, a.hierarchy + assert_not_same list, a.hierarchy(true) + end + +end -- libgit2 0.21.2