Chris@909: module CollectiveIdea #:nodoc: Chris@909: module Acts #:nodoc: Chris@909: module NestedSet #:nodoc: Chris@909: def self.included(base) Chris@909: base.extend(SingletonMethods) Chris@909: end Chris@909: Chris@909: # This acts provides Nested Set functionality. Nested Set is a smart way to implement Chris@909: # an _ordered_ tree, with the added feature that you can select the children and all of their Chris@909: # descendants with a single query. The drawback is that insertion or move need some complex Chris@909: # sql queries. But everything is done here by this module! Chris@909: # Chris@909: # Nested sets are appropriate each time you want either an orderd tree (menus, Chris@909: # commercial categories) or an efficient way of querying big trees (threaded posts). Chris@909: # Chris@909: # == API Chris@909: # Chris@909: # Methods names are aligned with acts_as_tree as much as possible, to make replacment from one Chris@909: # by another easier, except for the creation: Chris@909: # Chris@909: # in acts_as_tree: Chris@909: # item.children.create(:name => "child1") Chris@909: # Chris@909: # in acts_as_nested_set: Chris@909: # # adds a new item at the "end" of the tree, i.e. with child.left = max(tree.right)+1 Chris@909: # child = MyClass.new(:name => "child1") Chris@909: # child.save Chris@909: # # now move the item to its right place Chris@909: # child.move_to_child_of my_item Chris@909: # Chris@909: # You can pass an id or an object to: Chris@909: # * #move_to_child_of Chris@909: # * #move_to_right_of Chris@909: # * #move_to_left_of Chris@909: # Chris@909: module SingletonMethods Chris@909: # Configuration options are: Chris@909: # Chris@909: # * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id) Chris@909: # * +:left_column+ - column name for left boundry data, default "lft" Chris@909: # * +:right_column+ - column name for right boundry data, default "rgt" Chris@909: # * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id" Chris@909: # (if it hasn't been already) and use that as the foreign key restriction. You Chris@909: # can also pass an array to scope by multiple attributes. Chris@909: # Example: acts_as_nested_set :scope => [:notable_id, :notable_type] Chris@909: # * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the Chris@909: # child objects are destroyed alongside this object by calling their destroy Chris@909: # method. If set to :delete_all (default), all the child objects are deleted Chris@909: # without calling their destroy method. Chris@909: # Chris@909: # See CollectiveIdea::Acts::NestedSet::ClassMethods for a list of class methods and Chris@909: # CollectiveIdea::Acts::NestedSet::InstanceMethods for a list of instance methods added Chris@909: # to acts_as_nested_set models Chris@909: def acts_as_nested_set(options = {}) Chris@909: options = { Chris@909: :parent_column => 'parent_id', Chris@909: :left_column => 'lft', Chris@909: :right_column => 'rgt', Chris@909: :order => 'id', Chris@909: :dependent => :delete_all, # or :destroy Chris@909: }.merge(options) Chris@909: Chris@909: if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/ Chris@909: options[:scope] = "#{options[:scope]}_id".intern Chris@909: end Chris@909: Chris@909: write_inheritable_attribute :acts_as_nested_set_options, options Chris@909: class_inheritable_reader :acts_as_nested_set_options Chris@909: Chris@909: include Comparable Chris@909: include Columns Chris@909: include InstanceMethods Chris@909: extend Columns Chris@909: extend ClassMethods Chris@909: Chris@909: # no bulk assignment Chris@909: attr_protected left_column_name.intern, Chris@909: right_column_name.intern, Chris@909: parent_column_name.intern Chris@909: Chris@909: before_create :set_default_left_and_right Chris@909: before_destroy :prune_from_tree Chris@909: Chris@909: # no assignment to structure fields Chris@909: [left_column_name, right_column_name, parent_column_name].each do |column| Chris@909: module_eval <<-"end_eval", __FILE__, __LINE__ Chris@909: def #{column}=(x) Chris@909: raise ActiveRecord::ActiveRecordError, "Unauthorized assignment to #{column}: it's an internal field handled by acts_as_nested_set code, use move_to_* methods instead." Chris@909: end Chris@909: end_eval Chris@909: end Chris@909: Chris@909: named_scope :roots, :conditions => {parent_column_name => nil}, :order => quoted_left_column_name Chris@909: named_scope :leaves, :conditions => "#{quoted_right_column_name} - #{quoted_left_column_name} = 1", :order => quoted_left_column_name Chris@909: if self.respond_to?(:define_callbacks) Chris@909: define_callbacks("before_move", "after_move") Chris@909: end Chris@909: Chris@909: Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: module ClassMethods Chris@909: Chris@909: # Returns the first root Chris@909: def root Chris@909: roots.find(:first) Chris@909: end Chris@909: Chris@909: def valid? Chris@909: left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid? Chris@909: end Chris@909: Chris@909: def left_and_rights_valid? Chris@909: count( Chris@909: :joins => "LEFT OUTER JOIN #{quoted_table_name} AS parent ON " + Chris@909: "#{quoted_table_name}.#{quoted_parent_column_name} = parent.#{primary_key}", Chris@909: :conditions => Chris@909: "#{quoted_table_name}.#{quoted_left_column_name} IS NULL OR " + Chris@909: "#{quoted_table_name}.#{quoted_right_column_name} IS NULL OR " + Chris@909: "#{quoted_table_name}.#{quoted_left_column_name} >= " + Chris@909: "#{quoted_table_name}.#{quoted_right_column_name} OR " + Chris@909: "(#{quoted_table_name}.#{quoted_parent_column_name} IS NOT NULL AND " + Chris@909: "(#{quoted_table_name}.#{quoted_left_column_name} <= parent.#{quoted_left_column_name} OR " + Chris@909: "#{quoted_table_name}.#{quoted_right_column_name} >= parent.#{quoted_right_column_name}))" Chris@909: ) == 0 Chris@909: end Chris@909: Chris@909: def no_duplicates_for_columns? Chris@909: scope_string = Array(acts_as_nested_set_options[:scope]).map do |c| Chris@909: connection.quote_column_name(c) Chris@909: end.push(nil).join(", ") Chris@909: [quoted_left_column_name, quoted_right_column_name].all? do |column| Chris@909: # No duplicates Chris@909: find(:first, Chris@909: :select => "#{scope_string}#{column}, COUNT(#{column})", Chris@909: :group => "#{scope_string}#{column} Chris@909: HAVING COUNT(#{column}) > 1").nil? Chris@909: end Chris@909: end Chris@909: Chris@909: # Wrapper for each_root_valid? that can deal with scope. Chris@909: def all_roots_valid? Chris@909: if acts_as_nested_set_options[:scope] Chris@909: roots(:group => scope_column_names).group_by{|record| scope_column_names.collect{|col| record.send(col.to_sym)}}.all? do |scope, grouped_roots| Chris@909: each_root_valid?(grouped_roots) Chris@909: end Chris@909: else Chris@909: each_root_valid?(roots) Chris@909: end Chris@909: end Chris@909: Chris@909: def each_root_valid?(roots_to_validate) Chris@909: left = right = 0 Chris@909: roots_to_validate.all? do |root| Chris@909: (root.left > left && root.right > right).tap do Chris@909: left = root.left Chris@909: right = root.right Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: # Rebuilds the left & rights if unset or invalid. Also very useful for converting from acts_as_tree. Chris@909: def rebuild!(force=false) Chris@909: # Don't rebuild a valid tree. Chris@909: # valid? doesn't strictly validate the tree Chris@909: return true if !force && valid? Chris@909: Chris@909: scope = lambda{|node|} Chris@909: if acts_as_nested_set_options[:scope] Chris@909: scope = lambda{|node| Chris@909: scope_column_names.inject(""){|str, column_name| Chris@909: str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} " Chris@909: } Chris@909: } Chris@909: end Chris@909: indices = {} Chris@909: Chris@909: set_left_and_rights = lambda do |node| Chris@909: # set left Chris@909: node[left_column_name] = indices[scope.call(node)] += 1 Chris@909: # find Chris@909: find(:all, :conditions => ["#{quoted_parent_column_name} = ? #{scope.call(node)}", node], :order => "#{quoted_left_column_name}, #{quoted_right_column_name}, #{acts_as_nested_set_options[:order]}").each{|n| set_left_and_rights.call(n) } Chris@909: # set right Chris@909: node[right_column_name] = indices[scope.call(node)] += 1 Chris@909: node.save! Chris@909: end Chris@909: Chris@909: # Find root node(s) Chris@909: root_nodes = find(:all, :conditions => "#{quoted_parent_column_name} IS NULL", :order => "#{quoted_left_column_name}, #{quoted_right_column_name}, #{acts_as_nested_set_options[:order]}").each do |root_node| Chris@909: # setup index for this scope Chris@909: indices[scope.call(root_node)] ||= 0 Chris@909: set_left_and_rights.call(root_node) Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: # Mixed into both classes and instances to provide easy access to the column names Chris@909: module Columns Chris@909: def left_column_name Chris@909: acts_as_nested_set_options[:left_column] Chris@909: end Chris@909: Chris@909: def right_column_name Chris@909: acts_as_nested_set_options[:right_column] Chris@909: end Chris@909: Chris@909: def parent_column_name Chris@909: acts_as_nested_set_options[:parent_column] Chris@909: end Chris@909: Chris@909: def scope_column_names Chris@909: Array(acts_as_nested_set_options[:scope]) Chris@909: end Chris@909: Chris@909: def quoted_left_column_name Chris@909: connection.quote_column_name(left_column_name) Chris@909: end Chris@909: Chris@909: def quoted_right_column_name Chris@909: connection.quote_column_name(right_column_name) Chris@909: end Chris@909: Chris@909: def quoted_parent_column_name Chris@909: connection.quote_column_name(parent_column_name) Chris@909: end Chris@909: Chris@909: def quoted_scope_column_names Chris@909: scope_column_names.collect {|column_name| connection.quote_column_name(column_name) } Chris@909: end Chris@909: end Chris@909: Chris@909: # Any instance method that returns a collection makes use of Rails 2.1's named_scope (which is bundled for Rails 2.0), so it can be treated as a finder. Chris@909: # Chris@909: # category.self_and_descendants.count Chris@909: # category.ancestors.find(:all, :conditions => "name like '%foo%'") Chris@909: module InstanceMethods Chris@909: # Value of the parent column Chris@909: def parent_id Chris@909: self[parent_column_name] Chris@909: end Chris@909: Chris@909: # Value of the left column Chris@909: def left Chris@909: self[left_column_name] Chris@909: end Chris@909: Chris@909: # Value of the right column Chris@909: def right Chris@909: self[right_column_name] Chris@909: end Chris@909: Chris@909: # Returns true if this is a root node. Chris@909: def root? Chris@909: parent_id.nil? Chris@909: end Chris@909: Chris@909: def leaf? Chris@909: new_record? || (right - left == 1) Chris@909: end Chris@909: Chris@909: # Returns true is this is a child node Chris@909: def child? Chris@909: !parent_id.nil? Chris@909: end Chris@909: Chris@909: # order by left column Chris@909: def <=>(x) Chris@909: left <=> x.left Chris@909: end Chris@909: Chris@909: # Redefine to act like active record Chris@909: def ==(comparison_object) Chris@909: comparison_object.equal?(self) || Chris@909: (comparison_object.instance_of?(self.class) && Chris@909: comparison_object.id == id && Chris@909: !comparison_object.new_record?) Chris@909: end Chris@909: Chris@909: # Returns root Chris@909: def root Chris@909: self_and_ancestors.find(:first) Chris@909: end Chris@909: Chris@909: # Returns the immediate parent Chris@909: def parent Chris@909: nested_set_scope.find_by_id(parent_id) if parent_id Chris@909: end Chris@909: Chris@909: # Returns the array of all parents and self Chris@909: def self_and_ancestors Chris@909: nested_set_scope.scoped :conditions => [ Chris@909: "#{self.class.table_name}.#{quoted_left_column_name} <= ? AND #{self.class.table_name}.#{quoted_right_column_name} >= ?", left, right Chris@909: ] Chris@909: end Chris@909: Chris@909: # Returns an array of all parents Chris@909: def ancestors Chris@909: without_self self_and_ancestors Chris@909: end Chris@909: Chris@909: # Returns the array of all children of the parent, including self Chris@909: def self_and_siblings Chris@909: nested_set_scope.scoped :conditions => {parent_column_name => parent_id} Chris@909: end Chris@909: Chris@909: # Returns the array of all children of the parent, except self Chris@909: def siblings Chris@909: without_self self_and_siblings Chris@909: end Chris@909: Chris@909: # Returns a set of all of its nested children which do not have children Chris@909: def leaves Chris@909: descendants.scoped :conditions => "#{self.class.table_name}.#{quoted_right_column_name} - #{self.class.table_name}.#{quoted_left_column_name} = 1" Chris@909: end Chris@909: Chris@909: # Returns the level of this object in the tree Chris@909: # root level is 0 Chris@909: def level Chris@909: parent_id.nil? ? 0 : ancestors.count Chris@909: end Chris@909: Chris@909: # Returns a set of itself and all of its nested children Chris@909: def self_and_descendants Chris@909: nested_set_scope.scoped :conditions => [ Chris@909: "#{self.class.table_name}.#{quoted_left_column_name} >= ? AND #{self.class.table_name}.#{quoted_right_column_name} <= ?", left, right Chris@909: ] Chris@909: end Chris@909: Chris@909: # Returns a set of all of its children and nested children Chris@909: def descendants Chris@909: without_self self_and_descendants Chris@909: end Chris@909: Chris@909: # Returns a set of only this entry's immediate children Chris@909: def children Chris@909: nested_set_scope.scoped :conditions => {parent_column_name => self} Chris@909: end Chris@909: Chris@909: def is_descendant_of?(other) Chris@909: other.left < self.left && self.left < other.right && same_scope?(other) Chris@909: end Chris@909: Chris@909: def is_or_is_descendant_of?(other) Chris@909: other.left <= self.left && self.left < other.right && same_scope?(other) Chris@909: end Chris@909: Chris@909: def is_ancestor_of?(other) Chris@909: self.left < other.left && other.left < self.right && same_scope?(other) Chris@909: end Chris@909: Chris@909: def is_or_is_ancestor_of?(other) Chris@909: self.left <= other.left && other.left < self.right && same_scope?(other) Chris@909: end Chris@909: Chris@909: # Check if other model is in the same scope Chris@909: def same_scope?(other) Chris@909: Array(acts_as_nested_set_options[:scope]).all? do |attr| Chris@909: self.send(attr) == other.send(attr) Chris@909: end Chris@909: end Chris@909: Chris@909: # Find the first sibling to the left Chris@909: def left_sibling Chris@909: siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} < ?", left], Chris@909: :order => "#{self.class.table_name}.#{quoted_left_column_name} DESC") Chris@909: end Chris@909: Chris@909: # Find the first sibling to the right Chris@909: def right_sibling Chris@909: siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} > ?", left]) Chris@909: end Chris@909: Chris@909: # Shorthand method for finding the left sibling and moving to the left of it. Chris@909: def move_left Chris@909: move_to_left_of left_sibling Chris@909: end Chris@909: Chris@909: # Shorthand method for finding the right sibling and moving to the right of it. Chris@909: def move_right Chris@909: move_to_right_of right_sibling Chris@909: end Chris@909: Chris@909: # Move the node to the left of another node (you can pass id only) Chris@909: def move_to_left_of(node) Chris@909: move_to node, :left Chris@909: end Chris@909: Chris@909: # Move the node to the left of another node (you can pass id only) Chris@909: def move_to_right_of(node) Chris@909: move_to node, :right Chris@909: end Chris@909: Chris@909: # Move the node to the child of another node (you can pass id only) Chris@909: def move_to_child_of(node) Chris@909: move_to node, :child Chris@909: end Chris@909: Chris@909: # Move the node to root nodes Chris@909: def move_to_root Chris@909: move_to nil, :root Chris@909: end Chris@909: Chris@909: def move_possible?(target) Chris@909: self != target && # Can't target self Chris@909: same_scope?(target) && # can't be in different scopes Chris@909: # !(left..right).include?(target.left..target.right) # this needs tested more Chris@909: # detect impossible move Chris@909: !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right)) Chris@909: end Chris@909: Chris@909: def to_text Chris@909: self_and_descendants.map do |node| Chris@909: "#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})" Chris@909: end.join("\n") Chris@909: end Chris@909: Chris@909: protected Chris@909: Chris@909: def without_self(scope) Chris@909: scope.scoped :conditions => ["#{self.class.table_name}.#{self.class.primary_key} != ?", self] Chris@909: end Chris@909: Chris@909: # All nested set queries should use this nested_set_scope, which performs finds on Chris@909: # the base ActiveRecord class, using the :scope declared in the acts_as_nested_set Chris@909: # declaration. Chris@909: def nested_set_scope Chris@909: options = {:order => "#{self.class.table_name}.#{quoted_left_column_name}"} Chris@909: scopes = Array(acts_as_nested_set_options[:scope]) Chris@909: options[:conditions] = scopes.inject({}) do |conditions,attr| Chris@909: conditions.merge attr => self[attr] Chris@909: end unless scopes.empty? Chris@909: self.class.base_class.scoped options Chris@909: end Chris@909: Chris@909: # on creation, set automatically lft and rgt to the end of the tree Chris@909: def set_default_left_and_right Chris@909: maxright = nested_set_scope.maximum(right_column_name) || 0 Chris@909: # adds the new node to the right of all existing nodes Chris@909: self[left_column_name] = maxright + 1 Chris@909: self[right_column_name] = maxright + 2 Chris@909: end Chris@909: Chris@909: # Prunes a branch off of the tree, shifting all of the elements on the right Chris@909: # back to the left so the counts still work. Chris@909: def prune_from_tree Chris@909: return if right.nil? || left.nil? || !self.class.exists?(id) Chris@909: Chris@909: self.class.base_class.transaction do Chris@909: reload_nested_set Chris@909: if acts_as_nested_set_options[:dependent] == :destroy Chris@909: children.each(&:destroy) Chris@909: else Chris@909: nested_set_scope.send(:delete_all, Chris@909: ["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?", Chris@909: left, right] Chris@909: ) Chris@909: end Chris@909: reload_nested_set Chris@909: diff = right - left + 1 Chris@909: nested_set_scope.update_all( Chris@909: ["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff], Chris@909: ["#{quoted_left_column_name} >= ?", right] Chris@909: ) Chris@909: nested_set_scope.update_all( Chris@909: ["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff], Chris@909: ["#{quoted_right_column_name} >= ?", right] Chris@909: ) Chris@909: end Chris@909: Chris@909: # Reload is needed because children may have updated their parent (self) during deletion. Chris@909: reload Chris@909: end Chris@909: Chris@909: # reload left, right, and parent Chris@909: def reload_nested_set Chris@909: reload(:select => "#{quoted_left_column_name}, " + Chris@909: "#{quoted_right_column_name}, #{quoted_parent_column_name}") Chris@909: end Chris@909: Chris@909: def move_to(target, position) Chris@909: raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record? Chris@909: return if callback(:before_move) == false Chris@909: transaction do Chris@909: if target.is_a? self.class.base_class Chris@909: target.reload_nested_set Chris@909: elsif position != :root Chris@909: # load object if node is not an object Chris@909: target = nested_set_scope.find(target) Chris@909: end Chris@909: self.reload_nested_set Chris@909: Chris@909: unless position == :root || move_possible?(target) Chris@909: raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree." Chris@909: end Chris@909: Chris@909: bound = case position Chris@909: when :child; target[right_column_name] Chris@909: when :left; target[left_column_name] Chris@909: when :right; target[right_column_name] + 1 Chris@909: when :root; 1 Chris@909: else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)." Chris@909: end Chris@909: Chris@909: if bound > self[right_column_name] Chris@909: bound = bound - 1 Chris@909: other_bound = self[right_column_name] + 1 Chris@909: else Chris@909: other_bound = self[left_column_name] - 1 Chris@909: end Chris@909: Chris@909: # there would be no change Chris@909: return if bound == self[right_column_name] || bound == self[left_column_name] Chris@909: Chris@909: # we have defined the boundaries of two non-overlapping intervals, Chris@909: # so sorting puts both the intervals and their boundaries in order Chris@909: a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort Chris@909: Chris@909: new_parent = case position Chris@909: when :child; target.id Chris@909: when :root; nil Chris@909: else target[parent_column_name] Chris@909: end Chris@909: Chris@909: self.class.base_class.update_all([ Chris@909: "#{quoted_left_column_name} = CASE " + Chris@909: "WHEN #{quoted_left_column_name} BETWEEN :a AND :b " + Chris@909: "THEN #{quoted_left_column_name} + :d - :b " + Chris@909: "WHEN #{quoted_left_column_name} BETWEEN :c AND :d " + Chris@909: "THEN #{quoted_left_column_name} + :a - :c " + Chris@909: "ELSE #{quoted_left_column_name} END, " + Chris@909: "#{quoted_right_column_name} = CASE " + Chris@909: "WHEN #{quoted_right_column_name} BETWEEN :a AND :b " + Chris@909: "THEN #{quoted_right_column_name} + :d - :b " + Chris@909: "WHEN #{quoted_right_column_name} BETWEEN :c AND :d " + Chris@909: "THEN #{quoted_right_column_name} + :a - :c " + Chris@909: "ELSE #{quoted_right_column_name} END, " + Chris@909: "#{quoted_parent_column_name} = CASE " + Chris@909: "WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " + Chris@909: "ELSE #{quoted_parent_column_name} END", Chris@909: {:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent} Chris@909: ], nested_set_scope.proxy_options[:conditions]) Chris@909: end Chris@909: target.reload_nested_set if target Chris@909: self.reload_nested_set Chris@909: callback(:after_move) Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: end Chris@909: end Chris@909: end