List methods for nested sets
Unfortunately better_nested_set (and acts_as_nested_set) lacks the list methods provided by acts_as_list. Here's a module that provides them.
I had been using acts_as_tree together with acts_as_list to make ordered nested lists. Recently I replaced acts_as_tree with the better_nested_set plugin, a formidable replacement that is much more efficient in database queries (it pulls the whole tree from the database at once). The nested set is also ordered, so there's no need for acts_as_list.
Unfortunately better_nested_set lacks the list methods provided by acts_as_list. Here's a module that provides them. It treats each branch of a tree as its own list, thus these methods are scoped by the local root.
I haven't bothered to make this a plugin. Just create a file lib/nested_set_list.rb and paste this code:
module NestedSetList
def first?
parent.nil? or parent.lft==self.lft-1
end
def last?
parent.nil? or parent.rgt==self.rgt+1
end
def higher_item
list = self_and_siblings
i = list.index(self)
i==0 ? self : list[ i-1 ]
end
def lower_item
list = self_and_siblings
i = list.index(self)
i==list.size-1 ? self : list[ i+1 ]
end
def move_higher
move_to_left_of( higher_item ) if higher_item
end
def move_lower
move_to_right_of( lower_item ) if lower_item
end
def move_to_top
move_to_left_of( self_and_siblings.first )
end
def move_to_bottom
move_to_right_of( self_and_siblings.last )
end
end
In your model, be sure to include it
acts_as_nested_set
include NestedSetList
Comments
>>
The version at http://agilewebdevelopment.com/plugins/betternestedset has all the methods listed above
>>
Actually, the SVN repository listed on that page (http://opensource.symetrie.com/svn/better_nested_set/trunk) is obsolete, and doesn't seem to contain these additions (at least, not in the trunk). As the first comment on that page indicates, the real, up-to-date repository can be found on RubyForge at:
http://rubyforge.org/scm/?group_id=2290
(Where it looks like Tim Olsen and a number of other developers have thoroughly overhauled the plugin.)
A casual glance indicates that /tags/release-1.0 and /tags/stable don't contain these changes, but /trunk does, mainly as method aliases. (For instance, higher_item is an alias for previous_sibling, last? is an alias for last_sibling? etc.)
New Comment