lost password?

home
•  xaraya
•  rails +
•  django
•  webdev
•  xamp
•  musings

rss
Tag this page
   

ยป Blogs that link here
last modified: Feb 21, 2008
(first posted: Feb 21, 2008)
(2331 Reads)
keywords: acts_as_list acts_as_nested_set
Permalink

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

 

List methods for nested sets

Posted by: Dr. Serge on March 10, 2008 10:57 AM
The version at http://agilewebdevelopment.com/plugins/betternestedset has all the methods listed above

#

List methods for nested sets

Posted by: Joseph Riesen on March 11, 2008 02:44 PM
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.)

#

Post a new comment

: This is not spam

Name :