Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Tree conditions now rely on nested set for performance reasons

  • Loading branch information...
commit 09a887d1afe840df37cf71d1b02e69f8892d35e1 1 parent 1134bf4
@binarylogic authored
View
2  lib/searchlogic.rb
@@ -48,7 +48,7 @@
# Condition
require "searchlogic/condition/base"
-require "searchlogic/condition/tree"
+require "searchlogic/condition/nested_set"
SEARCHLOGIC_CONDITIONS = [:begins_with, :blank, :child_of, :descendant_of, :ends_with, :equals, :greater_than, :greater_than_or_equal_to, :inclusive_descendant_of, :like, :nil, :not_begin_with, :not_blank, :not_end_with, :not_equal, :not_have_keywords, :not_nil, :keywords, :less_than, :less_than_or_equal_to, :sibling_of]
SEARCHLOGIC_CONDITIONS.each { |condition| require "searchlogic/condition/#{condition}" }
View
2  lib/searchlogic/condition/child_of.rb
@@ -1,6 +1,6 @@
module Searchlogic
module Condition
- class ChildOf < Tree
+ class ChildOf < NestedSet
def to_conditions(value)
parent_association = klass.reflect_on_association(:parent)
foreign_key_name = (parent_association && parent_association.options[:foreign_key]) || "parent_id"
View
21 lib/searchlogic/condition/descendant_of.rb
@@ -1,24 +1,11 @@
module Searchlogic
module Condition
- class DescendantOf < Tree
+ class DescendantOf < NestedSet
def to_conditions(value)
- # Wish I knew how to do this in SQL
- root = (value.is_a?(klass) ? value : klass.find(value)) rescue return
- strs = []
- subs = []
- all_children_ids(root).each do |child_id|
- strs << "#{quoted_table_name}.#{quote_column_name(klass.primary_key)} = ?"
- subs << child_id
- end
- [strs.join(" OR "), *subs]
+ condition = InclusiveDescendantOf.new(klass, options)
+ condition.value = value
+ merge_conditions(["#{quoted_table_name}.#{quote_column_name(klass.primary_key)} != ?", (value.is_a?(klass) ? value.send(klass.primary_key) : value)], condition.sanitize)
end
-
- private
- def all_children_ids(record)
- ids = record.children.collect { |child| child.send(klass.primary_key) }
- record.children.each { |child| ids += all_children_ids(child) }
- ids
- end
end
end
end
View
7 lib/searchlogic/condition/inclusive_descendant_of.rb
@@ -1,10 +1,9 @@
module Searchlogic
module Condition
- class InclusiveDescendantOf < Tree
+ class InclusiveDescendantOf < NestedSet
def to_conditions(value)
- condition = DescendantOf.new(klass, options)
- condition.value = value
- merge_conditions(["#{quoted_table_name}.#{quote_column_name(klass.primary_key)} = ?", (value.is_a?(klass) ? value.send(klass.primary_key) : value)], condition.sanitize, :any => true)
+ root = (value.is_a?(klass) ? value : klass.find(value)) rescue return
+ ["#{quoted_table_name}.#{quote_column_name(klass.left_column_name)} >= ? AND #{quoted_table_name}.#{quote_column_name(klass.right_column_name)} <= ?", root.left, root.right]
end
end
end
View
2  lib/searchlogic/condition/tree.rb → lib/searchlogic/condition/nested_set.rb
@@ -1,6 +1,6 @@
module Searchlogic
module Condition
- class Tree < Base # :nodoc:
+ class NestedSet < Base # :nodoc:
self.join_arrays_with_or = true
class << self
View
2  lib/searchlogic/condition/sibling_of.rb
@@ -1,6 +1,6 @@
module Searchlogic
module Condition
- class SiblingOf < Tree
+ class SiblingOf < NestedSet
def to_conditions(value)
parent_association = klass.reflect_on_association(:parent)
foreign_key_name = (parent_association && parent_association.options[:foreign_key]) || "parent_id"
View
9 test/active_record_tests/associations_test.rb
@@ -12,8 +12,8 @@ def test_has_many
assert_equal User, search.klass
assert_equal({:conditions => "\"users\".account_id = #{binary_logic.id}"}, search.scope)
- assert_equal [jennifer, ben], search.all
- assert_equal jennifer, search.first
+ assert_equal [ben, jennifer], search.all
+ assert_equal ben, search.first
assert_equal ((ben.id + jennifer.id) / 2.0), search.average("id")
assert_equal 2, search.count
@@ -70,10 +70,9 @@ def test_habtm
assert_kind_of Searchlogic::Search::Base, search
assert_equal User, search.klass
assert_equal({:conditions => "\"user_groups_users\".user_group_id = #{neco.id} ", :joins => "INNER JOIN \"user_groups_users\" ON \"users\".id = \"user_groups_users\".user_id"}, search.scope)
+ assert_equal [drew, ben], search.all
- assert_equal [ben, drew], search.all
-
- assert_equal ben, search.first
+ assert_equal drew, search.first
assert_equal ((ben.id + drew.id) / 2.0).to_s, search.average("id").to_s
assert_equal 2, search.count
View
6 test/condition_tests/descendant_of_test.rb
@@ -4,13 +4,9 @@ module ConditionTests
class DescendantOfTest < ActiveSupport::TestCase
def test_sanitize
ben = users(:ben)
- drew = users(:drew)
- jennifer = users(:jennifer)
- tren = users(:tren)
-
condition = Searchlogic::Condition::DescendantOf.new(User)
condition.value = ben
- assert_equal ["\"users\".\"id\" = ? OR \"users\".\"id\" = ? OR \"users\".\"id\" = ?", drew.id, tren.id, jennifer.id], condition.sanitize
+ assert_equal ["\"users\".\"id\" != ? AND \"users\".\"lft\" >= ? AND \"users\".\"rgt\" <= ?", ben.id, ben.left, ben.right], condition.sanitize
end
end
end
View
6 test/condition_tests/inclusive_descendant_of_test.rb
@@ -4,13 +4,9 @@ module ConditionTests
class InclusiveDescendantOfTest < ActiveSupport::TestCase
def test_sanitize
ben = users(:ben)
- drew = users(:drew)
- jennifer = users(:jennifer)
- tren = users(:tren)
-
condition = Searchlogic::Condition::InclusiveDescendantOf.new(User)
condition.value = ben
- assert_equal ["\"users\".\"id\" = ? OR \"users\".\"id\" = ? OR \"users\".\"id\" = ? OR \"users\".\"id\" = ?", ben.id, drew.id, tren.id, jennifer.id], condition.sanitize
+ assert_equal ["\"users\".\"lft\" >= ? AND \"users\".\"rgt\" <= ?", ben.left, ben.right], condition.sanitize
end
end
end
View
5 test/conditions_tests/magic_methods_test.rb
@@ -4,9 +4,6 @@ module ConditionsTests
class MagicMethodsTest < ActiveSupport::TestCase
def test_class_level_conditions
ben = users(:ben)
- drew = users(:drew)
- jennifer = users(:jennifer)
- tren = users(:tren)
conditions = Searchlogic::Cache::UserConditions.new
conditions.descendant_of = "21"
@@ -14,7 +11,7 @@ def test_class_level_conditions
conditions.descendant_of = ["21", "22"]
assert_equal [21, 22], conditions.descendant_of
conditions.descendant_of = ben
- assert_equal ["\"users\".\"id\" = ? OR \"users\".\"id\" = ? OR \"users\".\"id\" = ?", drew.id, tren.id, jennifer.id], conditions.sanitize
+ assert_equal ["\"users\".\"id\" != ? AND \"users\".\"lft\" >= ? AND \"users\".\"rgt\" <= ?", ben.id, ben.left, ben.right], conditions.sanitize
end
def test_virtual_columns
View
4 test/fixtures/orders.yml
@@ -1,11 +1,11 @@
bens_order:
- user: ben
+ user_id: 1
total: 500.23
description: A bunch of apple products, etc.
receipt: some binary text
drews_order:
- user: drew
+ user_id: 2
total: 2.12
description: Some more apple projects, ipod, etc
receipt: some more binary text
View
4 test/fixtures/user_groups.yml
@@ -1,7 +1,5 @@
neco:
name: NECO
- users: ben, drew
johnsons:
- name: Johnsons
- users: ben, jennifer
+ name: Johnsons
View
21 test/fixtures/users.yml
@@ -1,28 +1,43 @@
ben:
+ id: 1
account: binary_logic
+ lft: 1
+ rgt: 8
first_name: Ben
last_name: Johnson
active: true
bio: Totally awesome!
+ user_groups: neco, johnsons
drew:
+ id: 2
account: neco
- parent: ben
+ parent_id: 1
+ lft: 2
+ rgt: 5
first_name: Drew
last_name: Mills
active: false
bio: Totally not awesome!
+ user_groups: neco
jennifer:
+ id: 3
account: binary_logic
- parent: drew
+ parent_id: 2
+ lft: 3
+ rgt: 4
first_name: Jennifer
last_name: Hopkins
active: false
bio: Totally not awesome at all!
+ user_groups: johnsons
tren:
- parent: ben
+ id: 4
+ parent_id: 1
+ lft: 6
+ rgt: 7
first_name: Tren
last_name: Garfield
active: false
View
98 test/libs/acts_as_tree.rb
@@ -1,98 +0,0 @@
-module ActiveRecord
- module Acts
- module Tree
- def self.included(base)
- base.extend(ClassMethods)
- end
-
- # Specify this +acts_as+ extension if you want to model a tree structure by providing a parent association and a children
- # association. This requires that you have a foreign key column, which by default is called +parent_id+.
- #
- # class Category < ActiveRecord::Base
- # acts_as_tree :order => "name"
- # end
- #
- # Example:
- # root
- # \_ child1
- # \_ subchild1
- # \_ subchild2
- #
- # root = Category.create("name" => "root")
- # child1 = root.children.create("name" => "child1")
- # subchild1 = child1.children.create("name" => "subchild1")
- #
- # root.parent # => nil
- # child1.parent # => root
- # root.children # => [child1]
- # root.children.first.children.first # => subchild1
- #
- # In addition to the parent and children associations, the following instance methods are added to the class
- # after calling <tt>acts_as_tree</tt>:
- # * <tt>siblings</tt> - Returns all the children of the parent, excluding the current node (<tt>[subchild2]</tt> when called on <tt>subchild1</tt>)
- # * <tt>self_and_siblings</tt> - Returns all the children of the parent, including the current node (<tt>[subchild1, subchild2]</tt> when called on <tt>subchild1</tt>)
- # * <tt>ancestors</tt> - Returns all the ancestors of the current node (<tt>[child1, root]</tt> when called on <tt>subchild2</tt>)
- # * <tt>root</tt> - Returns the root of the current node (<tt>root</tt> when called on <tt>subchild2</tt>)
- module ClassMethods
- # Configuration options are:
- #
- # * <tt>foreign_key</tt> - specifies the column name to use for tracking of the tree (default: +parent_id+)
- # * <tt>order</tt> - makes it possible to sort the children according to this SQL snippet.
- # * <tt>counter_cache</tt> - keeps a count in a +children_count+ column if set to +true+ (default: +false+).
- def acts_as_tree(options = {})
- configuration = { :foreign_key => "parent_id", :order => nil, :counter_cache => nil }
- configuration.update(options) if options.is_a?(Hash)
-
- belongs_to :parent, :class_name => name, :foreign_key => configuration[:foreign_key], :counter_cache => configuration[:counter_cache]
- has_many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order], :dependent => :destroy
-
- class_eval <<-EOV
- include ActiveRecord::Acts::Tree::InstanceMethods
-
- def self.roots
- find(:all, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}})
- end
-
- def self.root
- find(:first, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}})
- end
- EOV
- end
- end
-
- module InstanceMethods
- # Returns list of ancestors, starting from parent until root.
- #
- # subchild1.ancestors # => [child1, root]
- def ancestors
- node, nodes = self, []
- nodes << node = node.parent while node.parent
- nodes
- end
-
- # Returns the root node of the tree.
- def root
- node = self
- node = node.parent while node.parent
- node
- end
-
- # Returns all siblings of the current node.
- #
- # subchild1.siblings # => [subchild2]
- def siblings
- self_and_siblings - [self]
- end
-
- # Returns all siblings and a reference to the current node.
- #
- # subchild1.self_and_siblings # => [subchild1, subchild2]
- def self_and_siblings
- parent ? parent.children : self.class.roots
- end
- end
- end
- end
-end
-
-ActiveRecord::Base.send :include, ActiveRecord::Acts::Tree
View
545 test/libs/awesome_nested_set.rb
@@ -0,0 +1,545 @@
+module CollectiveIdea #:nodoc:
+ module Acts #:nodoc:
+ module NestedSet #:nodoc:
+ def self.included(base)
+ base.extend(SingletonMethods)
+ end
+
+ # This acts provides Nested Set functionality. Nested Set is a smart way to implement
+ # an _ordered_ tree, with the added feature that you can select the children and all of their
+ # descendants with a single query. The drawback is that insertion or move need some complex
+ # sql queries. But everything is done here by this module!
+ #
+ # Nested sets are appropriate each time you want either an orderd tree (menus,
+ # commercial categories) or an efficient way of querying big trees (threaded posts).
+ #
+ # == API
+ #
+ # Methods names are aligned with acts_as_tree as much as possible, to make replacment from one
+ # by another easier, except for the creation:
+ #
+ # in acts_as_tree:
+ # item.children.create(:name => "child1")
+ #
+ # in acts_as_nested_set:
+ # # adds a new item at the "end" of the tree, i.e. with child.left = max(tree.right)+1
+ # child = MyClass.new(:name => "child1")
+ # child.save
+ # # now move the item to its right place
+ # child.move_to_child_of my_item
+ #
+ # You can pass an id or an object to:
+ # * <tt>#move_to_child_of</tt>
+ # * <tt>#move_to_right_of</tt>
+ # * <tt>#move_to_left_of</tt>
+ #
+ module SingletonMethods
+ # Configuration options are:
+ #
+ # * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id)
+ # * +:left_column+ - column name for left boundry data, default "lft"
+ # * +:right_column+ - column name for right boundry data, default "rgt"
+ # * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id"
+ # (if it hasn't been already) and use that as the foreign key restriction. You
+ # can also pass an array to scope by multiple attributes.
+ # Example: <tt>acts_as_nested_set :scope => [:notable_id, :notable_type]</tt>
+ # * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the
+ # child objects are destroyed alongside this object by calling their destroy
+ # method. If set to :delete_all (default), all the child objects are deleted
+ # without calling their destroy method.
+ #
+ # See CollectiveIdea::Acts::NestedSet::ClassMethods for a list of class methods and
+ # CollectiveIdea::Acts::NestedSet::InstanceMethods for a list of instance methods added
+ # to acts_as_nested_set models
+ def acts_as_nested_set(options = {})
+ options = {
+ :parent_column => 'parent_id',
+ :left_column => 'lft',
+ :right_column => 'rgt',
+ :dependent => :delete_all, # or :destroy
+ }.merge(options)
+
+ if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/
+ options[:scope] = "#{options[:scope]}_id".intern
+ end
+
+ write_inheritable_attribute :acts_as_nested_set_options, options
+ class_inheritable_reader :acts_as_nested_set_options
+
+ include InstanceMethods
+ include Comparable
+ include Columns
+ extend Columns
+ extend ClassMethods
+
+ # no bulk assignment
+ attr_protected left_column_name.intern,
+ right_column_name.intern,
+ parent_column_name.intern
+
+ before_create :set_default_left_and_right
+ before_destroy :prune_from_tree
+
+ # no assignment to structure fields
+ [left_column_name, right_column_name, parent_column_name].each do |column|
+ module_eval <<-"end_eval", __FILE__, __LINE__
+ def #{column}=(x)
+ raise ActiveRecord::ActiveRecordError, "Unauthorized assignment to #{column}: it's an internal field handled by acts_as_nested_set code, use move_to_* methods instead."
+ end
+ end_eval
+ end
+
+ named_scope :roots, :conditions => {parent_column_name => nil}, :order => quoted_left_column_name
+ named_scope :leaves, :conditions => "#{quoted_right_column_name} - #{quoted_left_column_name} = 1", :order => quoted_left_column_name
+ if self.respond_to?(:define_callbacks)
+ define_callbacks("before_move", "after_move")
+ end
+
+
+ end
+
+ end
+
+ module ClassMethods
+
+ # Returns the first root
+ def root
+ roots.find(:first)
+ end
+
+ def valid?
+ left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
+ end
+
+ def left_and_rights_valid?
+ count(
+ :joins => "LEFT OUTER JOIN #{quoted_table_name} AS parent ON " +
+ "#{quoted_table_name}.#{quoted_parent_column_name} = parent.#{primary_key}",
+ :conditions =>
+ "#{quoted_table_name}.#{quoted_left_column_name} IS NULL OR " +
+ "#{quoted_table_name}.#{quoted_right_column_name} IS NULL OR " +
+ "#{quoted_table_name}.#{quoted_left_column_name} >= " +
+ "#{quoted_table_name}.#{quoted_right_column_name} OR " +
+ "(#{quoted_table_name}.#{quoted_parent_column_name} IS NOT NULL AND " +
+ "(#{quoted_table_name}.#{quoted_left_column_name} <= parent.#{quoted_left_column_name} OR " +
+ "#{quoted_table_name}.#{quoted_right_column_name} >= parent.#{quoted_right_column_name}))"
+ ) == 0
+ end
+
+ def no_duplicates_for_columns?
+ scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
+ connection.quote_column_name(c)
+ end.push(nil).join(", ")
+ [quoted_left_column_name, quoted_right_column_name].all? do |column|
+ # No duplicates
+ find(:first,
+ :select => "#{scope_string}#{column}, COUNT(#{column})",
+ :group => "#{scope_string}#{column}
+ HAVING COUNT(#{column}) > 1").nil?
+ end
+ end
+
+ # Wrapper for each_root_valid? that can deal with scope.
+ def all_roots_valid?
+ if acts_as_nested_set_options[:scope]
+ roots(:group => scope_column_names).group_by{|record| scope_column_names.collect{|col| record.send(col.to_sym)}}.all? do |scope, grouped_roots|
+ each_root_valid?(grouped_roots)
+ end
+ else
+ each_root_valid?(roots)
+ end
+ end
+
+ def each_root_valid?(roots_to_validate)
+ left = right = 0
+ roots_to_validate.all? do |root|
+ returning(root.left > left && root.right > right) do
+ left = root.left
+ right = root.right
+ end
+ end
+ end
+
+ # Rebuilds the left & rights if unset or invalid. Also very useful for converting from acts_as_tree.
+ def rebuild!
+ # Don't rebuild a valid tree.
+ return true if valid?
+
+ scope = lambda{}
+ if acts_as_nested_set_options[:scope]
+ scope = lambda{|node|
+ scope_column_names.inject(""){|str, column_name|
+ str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
+ }
+ }
+ end
+ indices = {}
+
+ set_left_and_rights = lambda do |node|
+ # set left
+ node[left_column_name] = indices[scope.call(node)] += 1
+ # find
+ find(:all, :conditions => ["#{quoted_parent_column_name} = ? #{scope.call(node)}", node], :order => "#{quoted_left_column_name}, #{quoted_right_column_name}, id").each{|n| set_left_and_rights.call(n) }
+ # set right
+ node[right_column_name] = indices[scope.call(node)] += 1
+ node.save!
+ end
+
+ # Find root node(s)
+ root_nodes = find(:all, :conditions => "#{quoted_parent_column_name} IS NULL", :order => "#{quoted_left_column_name}, #{quoted_right_column_name}, id").each do |root_node|
+ # setup index for this scope
+ indices[scope.call(root_node)] ||= 0
+ set_left_and_rights.call(root_node)
+ end
+ end
+ end
+
+ # Mixed into both classes and instances to provide easy access to the column names
+ module Columns
+ def left_column_name
+ acts_as_nested_set_options[:left_column]
+ end
+
+ def right_column_name
+ acts_as_nested_set_options[:right_column]
+ end
+
+ def parent_column_name
+ acts_as_nested_set_options[:parent_column]
+ end
+
+ def scope_column_names
+ Array(acts_as_nested_set_options[:scope])
+ end
+
+ def quoted_left_column_name
+ connection.quote_column_name(left_column_name)
+ end
+
+ def quoted_right_column_name
+ connection.quote_column_name(right_column_name)
+ end
+
+ def quoted_parent_column_name
+ connection.quote_column_name(parent_column_name)
+ end
+
+ def quoted_scope_column_names
+ scope_column_names.collect {|column_name| connection.quote_column_name(column_name) }
+ end
+ end
+
+ # 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.
+ #
+ # category.self_and_descendants.count
+ # category.ancestors.find(:all, :conditions => "name like '%foo%'")
+ module InstanceMethods
+ # Value of the parent column
+ def parent_id
+ self[parent_column_name]
+ end
+
+ # Value of the left column
+ def left
+ self[left_column_name]
+ end
+
+ # Value of the right column
+ def right
+ self[right_column_name]
+ end
+
+ # Returns true if this is a root node.
+ def root?
+ parent_id.nil?
+ end
+
+ def leaf?
+ right - left == 1
+ end
+
+ # Returns true is this is a child node
+ def child?
+ !parent_id.nil?
+ end
+
+ # order by left column
+ def <=>(x)
+ left <=> x.left
+ end
+
+ # Returns root
+ def root
+ self_and_ancestors.find(:first)
+ end
+
+ # Returns the immediate parent
+ def parent
+ nested_set_scope.find_by_id(parent_id) if parent_id
+ end
+
+ # Returns the array of all parents and self
+ def self_and_ancestors
+ nested_set_scope.scoped :conditions => [
+ "#{self.class.table_name}.#{quoted_left_column_name} <= ? AND #{self.class.table_name}.#{quoted_right_column_name} >= ?", left, right
+ ]
+ end
+
+ # Returns an array of all parents
+ def ancestors
+ without_self self_and_ancestors
+ end
+
+ # Returns the array of all children of the parent, including self
+ def self_and_siblings
+ nested_set_scope.scoped :conditions => {parent_column_name => parent_id}
+ end
+
+ # Returns the array of all children of the parent, except self
+ def siblings
+ without_self self_and_siblings
+ end
+
+ # Returns a set of all of its nested children which do not have children
+ def leaves
+ descendants.scoped :conditions => "#{self.class.table_name}.#{quoted_right_column_name} - #{self.class.table_name}.#{quoted_left_column_name} = 1"
+ end
+
+ # Returns the level of this object in the tree
+ # root level is 0
+ def level
+ parent_id.nil? ? 0 : ancestors.count
+ end
+
+ # Returns a set of itself and all of its nested children
+ def self_and_descendants
+ nested_set_scope.scoped :conditions => [
+ "#{self.class.table_name}.#{quoted_left_column_name} >= ? AND #{self.class.table_name}.#{quoted_right_column_name} <= ?", left, right
+ ]
+ end
+
+ # Returns a set of all of its children and nested children
+ def descendants
+ without_self self_and_descendants
+ end
+
+ # Returns a set of only this entry's immediate children
+ def children
+ nested_set_scope.scoped :conditions => {parent_column_name => self}
+ end
+
+ def is_descendant_of?(other)
+ other.left < self.left && self.left < other.right && same_scope?(other)
+ end
+
+ def is_or_is_descendant_of?(other)
+ other.left <= self.left && self.left < other.right && same_scope?(other)
+ end
+
+ def is_ancestor_of?(other)
+ self.left < other.left && other.left < self.right && same_scope?(other)
+ end
+
+ def is_or_is_ancestor_of?(other)
+ self.left <= other.left && other.left < self.right && same_scope?(other)
+ end
+
+ # Check if other model is in the same scope
+ def same_scope?(other)
+ Array(acts_as_nested_set_options[:scope]).all? do |attr|
+ self.send(attr) == other.send(attr)
+ end
+ end
+
+ # Find the first sibling to the left
+ def left_sibling
+ siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} < ?", left],
+ :order => "#{self.class.table_name}.#{quoted_left_column_name} DESC")
+ end
+
+ # Find the first sibling to the right
+ def right_sibling
+ siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} > ?", left])
+ end
+
+ # Shorthand method for finding the left sibling and moving to the left of it.
+ def move_left
+ move_to_left_of left_sibling
+ end
+
+ # Shorthand method for finding the right sibling and moving to the right of it.
+ def move_right
+ move_to_right_of right_sibling
+ end
+
+ # Move the node to the left of another node (you can pass id only)
+ def move_to_left_of(node)
+ move_to node, :left
+ end
+
+ # Move the node to the left of another node (you can pass id only)
+ def move_to_right_of(node)
+ move_to node, :right
+ end
+
+ # Move the node to the child of another node (you can pass id only)
+ def move_to_child_of(node)
+ move_to node, :child
+ end
+
+ # Move the node to root nodes
+ def move_to_root
+ move_to nil, :root
+ end
+
+ def move_possible?(target)
+ self != target && # Can't target self
+ same_scope?(target) && # can't be in different scopes
+ # !(left..right).include?(target.left..target.right) # this needs tested more
+ # detect impossible move
+ !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))
+ end
+
+ def to_text
+ self_and_descendants.map do |node|
+ "#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})"
+ end.join("\n")
+ end
+
+ protected
+
+ def without_self(scope)
+ scope.scoped :conditions => ["#{self.class.table_name}.#{self.class.primary_key} != ?", self]
+ end
+
+ # All nested set queries should use this nested_set_scope, which performs finds on
+ # the base ActiveRecord class, using the :scope declared in the acts_as_nested_set
+ # declaration.
+ def nested_set_scope
+ options = {:order => quoted_left_column_name}
+ scopes = Array(acts_as_nested_set_options[:scope])
+ options[:conditions] = scopes.inject({}) do |conditions,attr|
+ conditions.merge attr => self[attr]
+ end unless scopes.empty?
+ self.class.base_class.scoped options
+ end
+
+ # on creation, set automatically lft and rgt to the end of the tree
+ def set_default_left_and_right
+ maxright = nested_set_scope.maximum(right_column_name) || 0
+ # adds the new node to the right of all existing nodes
+ self[left_column_name] = maxright + 1
+ self[right_column_name] = maxright + 2
+ end
+
+ # Prunes a branch off of the tree, shifting all of the elements on the right
+ # back to the left so the counts still work.
+ def prune_from_tree
+ return if right.nil? || left.nil?
+ diff = right - left + 1
+
+ delete_method = acts_as_nested_set_options[:dependent] == :destroy ?
+ :destroy_all : :delete_all
+
+ self.class.base_class.transaction do
+ nested_set_scope.send(delete_method,
+ ["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?",
+ left, right]
+ )
+ nested_set_scope.update_all(
+ ["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff],
+ ["#{quoted_left_column_name} >= ?", right]
+ )
+ nested_set_scope.update_all(
+ ["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff],
+ ["#{quoted_right_column_name} >= ?", right]
+ )
+ end
+ end
+
+ # reload left, right, and parent
+ def reload_nested_set
+ reload(:select => "#{quoted_left_column_name}, " +
+ "#{quoted_right_column_name}, #{quoted_parent_column_name}")
+ end
+
+ def move_to(target, position)
+ raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record?
+ return if callback(:before_move) == false
+ transaction do
+ if target.is_a? self.class.base_class
+ target.reload_nested_set
+ elsif position != :root
+ # load object if node is not an object
+ target = nested_set_scope.find(target)
+ end
+ self.reload_nested_set
+
+ unless position == :root || move_possible?(target)
+ raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree."
+ end
+
+ bound = case position
+ when :child; target[right_column_name]
+ when :left; target[left_column_name]
+ when :right; target[right_column_name] + 1
+ when :root; 1
+ else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)."
+ end
+
+ if bound > self[right_column_name]
+ bound = bound - 1
+ other_bound = self[right_column_name] + 1
+ else
+ other_bound = self[left_column_name] - 1
+ end
+
+ # there would be no change
+ return if bound == self[right_column_name] || bound == self[left_column_name]
+
+ # we have defined the boundaries of two non-overlapping intervals,
+ # so sorting puts both the intervals and their boundaries in order
+ a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort
+
+ new_parent = case position
+ when :child; target.id
+ when :root; nil
+ else target[parent_column_name]
+ end
+
+ self.class.base_class.update_all([
+ "#{quoted_left_column_name} = CASE " +
+ "WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
+ "THEN #{quoted_left_column_name} + :d - :b " +
+ "WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
+ "THEN #{quoted_left_column_name} + :a - :c " +
+ "ELSE #{quoted_left_column_name} END, " +
+ "#{quoted_right_column_name} = CASE " +
+ "WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
+ "THEN #{quoted_right_column_name} + :d - :b " +
+ "WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
+ "THEN #{quoted_right_column_name} + :a - :c " +
+ "ELSE #{quoted_right_column_name} END, " +
+ "#{quoted_parent_column_name} = CASE " +
+ "WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
+ "ELSE #{quoted_parent_column_name} END",
+ {:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent}
+ ], nested_set_scope.proxy_options[:conditions])
+ end
+ target.reload_nested_set if target
+ self.reload_nested_set
+ callback(:after_move)
+ end
+
+ end
+
+ end
+ end
+end
+
+
+require File.dirname(__FILE__) + '/awesome_nested_set/compatability'
+
+ActiveRecord::Base.class_eval do
+ include CollectiveIdea::Acts::NestedSet
+end
View
13 test/libs/awesome_nested_set/.autotest
@@ -0,0 +1,13 @@
+Autotest.add_hook :initialize do |at|
+ at.clear_mappings
+
+ at.add_mapping %r%^lib/(.*)\.rb$% do |_, m|
+ at.files_matching %r%^test/#{m[1]}_test.rb$%
+ end
+
+ at.add_mapping(%r%^test/.*\.rb$%) {|filename, _| filename }
+
+ at.add_mapping %r%^test/fixtures/(.*)s.yml% do |_, _|
+ at.files_matching %r%^test/.*\.rb$%
+ end
+end
View
5 test/libs/awesome_nested_set/.gitignore
@@ -0,0 +1,5 @@
+awesome_nested_set.sqlite3.db
+test/debug.log
+rdoc
+coverage
+pkg
View
29 test/libs/awesome_nested_set/compatability.rb
@@ -0,0 +1,29 @@
+# Rails <2.x doesn't define #except
+class Hash #:nodoc:
+ # Returns a new hash without the given keys.
+ def except(*keys)
+ clone.except!(*keys)
+ end unless method_defined?(:except)
+
+ # Replaces the hash without the given keys.
+ def except!(*keys)
+ keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
+ keys.each { |key| delete(key) }
+ self
+ end unless method_defined?(:except!)
+end
+
+# NamedScope is new to Rails 2.1
+unless defined? ActiveRecord::NamedScope
+ require 'awesome_nested_set/named_scope'
+ ActiveRecord::Base.class_eval do
+ include CollectiveIdea::NamedScope
+ end
+end
+
+# Rails 1.2.x doesn't define #quoted_table_name
+class ActiveRecord::Base #:nodoc:
+ def self.quoted_table_name
+ self.connection.quote_column_name(self.table_name)
+ end unless methods.include?('quoted_table_name')
+end
View
40 test/libs/awesome_nested_set/helper.rb
@@ -0,0 +1,40 @@
+module CollectiveIdea #:nodoc:
+ module Acts #:nodoc:
+ module NestedSet #:nodoc:
+ # This module provides some helpers for the model classes using acts_as_nested_set.
+ # It is included by default in all views.
+ #
+ module Helper
+ # Returns options for select.
+ # You can exclude some items from the tree.
+ # You can pass a block receiving an item and returning the string displayed in the select.
+ #
+ # == Params
+ # * +class_or_item+ - Class name or top level times
+ # * +mover+ - The item that is being move, used to exlude impossible moves
+ # * +&block+ - a block that will be used to display: { |item| ... item.name }
+ #
+ # == Usage
+ #
+ # <%= f.select :parent_id, nested_set_options(Category, @category) {|i|
+ # "#{'–' * i.level} #{i.name}"
+ # }) %>
+ #
+ def nested_set_options(class_or_item, mover = nil)
+ class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
+ items = Array(class_or_item)
+ result = []
+ items.each do |root|
+ result += root.self_and_descendants.map do |i|
+ if mover.nil? || mover.new_record? || mover.move_possible?(i)
+ [yield(i), i.id]
+ end
+ end.compact
+ end
+ result
+ end
+
+ end
+ end
+ end
+end
View
140 test/libs/awesome_nested_set/named_scope.rb
@@ -0,0 +1,140 @@
+# Taken from Rails 2.1
+module CollectiveIdea #:nodoc:
+ module NamedScope #:nodoc:
+ # All subclasses of ActiveRecord::Base have two named_scopes:
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly:
+ #
+ # Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)
+ #
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
+ # intermediate values (scopes) around as first-class objects is convenient.
+ def self.included(base)
+ base.class_eval do
+ extend ClassMethods
+ named_scope :scoped, lambda { |scope| scope }
+ end
+ end
+
+ module ClassMethods
+ def scopes
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
+ end
+
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'}
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
+ # end
+ #
+ # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
+ #
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
+ #
+ # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
+ #
+ # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to
+ # <tt>has_many</tt> associations. If,
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :shirts
+ # end
+ #
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
+ # only shirts.
+ #
+ # Named scopes can also be procedural.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :colored, lambda { |color|
+ # { :conditions => { :color => color } }
+ # }
+ # end
+ #
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
+ #
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'} do
+ # def dom_id
+ # 'red_shirts'
+ # end
+ # end
+ # end
+ #
+ #
+ # For testing complex named scopes, you can examine the scoping options using the
+ # <tt>proxy_options</tt> method on the proxy itself.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :colored, lambda { |color|
+ # { :conditions => { :color => color } }
+ # }
+ # end
+ #
+ # expected_options = { :conditions => { :colored => 'red' } }
+ # assert_equal expected_options, Shirt.colored('red').proxy_options
+ def named_scope(name, options = {}, &block)
+ scopes[name] = lambda do |parent_scope, *args|
+ Scope.new(parent_scope, case options
+ when Hash
+ options
+ when Proc
+ options.call(*args)
+ end, &block)
+ end
+ (class << self; self end).instance_eval do
+ define_method name do |*args|
+ scopes[name].call(self, *args)
+ end
+ end
+ end
+ end
+
+ class Scope
+ attr_reader :proxy_scope, :proxy_options
+ [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ }
+ delegate :scopes, :with_scope, :to => :proxy_scope
+
+ def initialize(proxy_scope, options, &block)
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
+ extend Module.new(&block) if block_given?
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
+ end
+
+ def reload
+ load_found; self
+ end
+
+ protected
+ def proxy_found
+ @found || load_found
+ end
+
+ private
+ def method_missing(method, *args, &block)
+ if scopes.include?(method)
+ scopes[method].call(self, *args)
+ else
+ with_scope :find => proxy_options do
+ proxy_scope.send(method, *args, &block)
+ end
+ end
+ end
+
+ def load_found
+ @found = find(:all)
+ end
+ end
+ end
+end
View
6 test/test_helper.rb
@@ -3,7 +3,7 @@
require "ruby-debug"
require "active_record"
require "active_record/fixtures"
-require File.dirname(__FILE__) + '/libs/acts_as_tree'
+require File.dirname(__FILE__) + '/libs/awesome_nested_set'
require File.dirname(__FILE__) + '/libs/rexml_fix'
require File.dirname(__FILE__) + '/../lib/searchlogic' unless defined?(Searchlogic)
@@ -34,6 +34,8 @@
t.datetime :updated_at
t.integer :account_id
t.integer :parent_id
+ t.integer :lft
+ t.integer :rgt
t.string :first_name
t.string :last_name
t.boolean :active
@@ -78,7 +80,7 @@ class UserGroup < ActiveRecord::Base
end
class User < ActiveRecord::Base
- acts_as_tree
+ acts_as_nested_set
belongs_to :account
has_many :orders, :dependent => :destroy
has_many :cats, :dependent => :destroy
Please sign in to comment.
Something went wrong with that request. Please try again.