annotate .svn/pristine/4f/4f45518942b2798afa2e5ae495723f19edb35bdd.svn-base @ 1327:287f201c2802 redmine-2.2-integration

Add italic
author Chris Cannam <chris.cannam@soundsoftware.ac.uk>
date Wed, 19 Jun 2013 20:56:22 +0100
parents 038ba2d95de8
children
rev   line source
Chris@1296 1 module CollectiveIdea #:nodoc:
Chris@1296 2 module Acts #:nodoc:
Chris@1296 3 module NestedSet #:nodoc:
Chris@1296 4
Chris@1296 5 # This acts provides Nested Set functionality. Nested Set is a smart way to implement
Chris@1296 6 # an _ordered_ tree, with the added feature that you can select the children and all of their
Chris@1296 7 # descendants with a single query. The drawback is that insertion or move need some complex
Chris@1296 8 # sql queries. But everything is done here by this module!
Chris@1296 9 #
Chris@1296 10 # Nested sets are appropriate each time you want either an orderd tree (menus,
Chris@1296 11 # commercial categories) or an efficient way of querying big trees (threaded posts).
Chris@1296 12 #
Chris@1296 13 # == API
Chris@1296 14 #
Chris@1296 15 # Methods names are aligned with acts_as_tree as much as possible to make replacment from one
Chris@1296 16 # by another easier.
Chris@1296 17 #
Chris@1296 18 # item.children.create(:name => "child1")
Chris@1296 19 #
Chris@1296 20
Chris@1296 21 # Configuration options are:
Chris@1296 22 #
Chris@1296 23 # * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id)
Chris@1296 24 # * +:left_column+ - column name for left boundry data, default "lft"
Chris@1296 25 # * +:right_column+ - column name for right boundry data, default "rgt"
Chris@1296 26 # * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id"
Chris@1296 27 # (if it hasn't been already) and use that as the foreign key restriction. You
Chris@1296 28 # can also pass an array to scope by multiple attributes.
Chris@1296 29 # Example: <tt>acts_as_nested_set :scope => [:notable_id, :notable_type]</tt>
Chris@1296 30 # * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the
Chris@1296 31 # child objects are destroyed alongside this object by calling their destroy
Chris@1296 32 # method. If set to :delete_all (default), all the child objects are deleted
Chris@1296 33 # without calling their destroy method.
Chris@1296 34 # * +:counter_cache+ adds a counter cache for the number of children.
Chris@1296 35 # defaults to false.
Chris@1296 36 # Example: <tt>acts_as_nested_set :counter_cache => :children_count</tt>
Chris@1296 37 #
Chris@1296 38 # See CollectiveIdea::Acts::NestedSet::Model::ClassMethods for a list of class methods and
Chris@1296 39 # CollectiveIdea::Acts::NestedSet::Model for a list of instance methods added
Chris@1296 40 # to acts_as_nested_set models
Chris@1296 41 def acts_as_nested_set(options = {})
Chris@1296 42 options = {
Chris@1296 43 :parent_column => 'parent_id',
Chris@1296 44 :left_column => 'lft',
Chris@1296 45 :right_column => 'rgt',
Chris@1296 46 :dependent => :delete_all, # or :destroy
Chris@1296 47 :counter_cache => false,
Chris@1296 48 :order => 'id'
Chris@1296 49 }.merge(options)
Chris@1296 50
Chris@1296 51 if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/
Chris@1296 52 options[:scope] = "#{options[:scope]}_id".intern
Chris@1296 53 end
Chris@1296 54
Chris@1296 55 class_attribute :acts_as_nested_set_options
Chris@1296 56 self.acts_as_nested_set_options = options
Chris@1296 57
Chris@1296 58 include CollectiveIdea::Acts::NestedSet::Model
Chris@1296 59 include Columns
Chris@1296 60 extend Columns
Chris@1296 61
Chris@1296 62 belongs_to :parent, :class_name => self.base_class.to_s,
Chris@1296 63 :foreign_key => parent_column_name,
Chris@1296 64 :counter_cache => options[:counter_cache],
Chris@1296 65 :inverse_of => :children
Chris@1296 66 has_many :children, :class_name => self.base_class.to_s,
Chris@1296 67 :foreign_key => parent_column_name, :order => left_column_name,
Chris@1296 68 :inverse_of => :parent,
Chris@1296 69 :before_add => options[:before_add],
Chris@1296 70 :after_add => options[:after_add],
Chris@1296 71 :before_remove => options[:before_remove],
Chris@1296 72 :after_remove => options[:after_remove]
Chris@1296 73
Chris@1296 74 attr_accessor :skip_before_destroy
Chris@1296 75
Chris@1296 76 before_create :set_default_left_and_right
Chris@1296 77 before_save :store_new_parent
Chris@1296 78 after_save :move_to_new_parent
Chris@1296 79 before_destroy :destroy_descendants
Chris@1296 80
Chris@1296 81 # no assignment to structure fields
Chris@1296 82 [left_column_name, right_column_name].each do |column|
Chris@1296 83 module_eval <<-"end_eval", __FILE__, __LINE__
Chris@1296 84 def #{column}=(x)
Chris@1296 85 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@1296 86 end
Chris@1296 87 end_eval
Chris@1296 88 end
Chris@1296 89
Chris@1296 90 define_model_callbacks :move
Chris@1296 91 end
Chris@1296 92
Chris@1296 93 module Model
Chris@1296 94 extend ActiveSupport::Concern
Chris@1296 95
Chris@1296 96 module ClassMethods
Chris@1296 97 # Returns the first root
Chris@1296 98 def root
Chris@1296 99 roots.first
Chris@1296 100 end
Chris@1296 101
Chris@1296 102 def roots
Chris@1296 103 where(parent_column_name => nil).order(quoted_left_column_name)
Chris@1296 104 end
Chris@1296 105
Chris@1296 106 def leaves
Chris@1296 107 where("#{quoted_right_column_name} - #{quoted_left_column_name} = 1").order(quoted_left_column_name)
Chris@1296 108 end
Chris@1296 109
Chris@1296 110 def valid?
Chris@1296 111 left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
Chris@1296 112 end
Chris@1296 113
Chris@1296 114 def left_and_rights_valid?
Chris@1296 115 joins("LEFT OUTER JOIN #{quoted_table_name} AS parent ON " +
Chris@1296 116 "#{quoted_table_name}.#{quoted_parent_column_name} = parent.#{primary_key}").
Chris@1296 117 where(
Chris@1296 118 "#{quoted_table_name}.#{quoted_left_column_name} IS NULL OR " +
Chris@1296 119 "#{quoted_table_name}.#{quoted_right_column_name} IS NULL OR " +
Chris@1296 120 "#{quoted_table_name}.#{quoted_left_column_name} >= " +
Chris@1296 121 "#{quoted_table_name}.#{quoted_right_column_name} OR " +
Chris@1296 122 "(#{quoted_table_name}.#{quoted_parent_column_name} IS NOT NULL AND " +
Chris@1296 123 "(#{quoted_table_name}.#{quoted_left_column_name} <= parent.#{quoted_left_column_name} OR " +
Chris@1296 124 "#{quoted_table_name}.#{quoted_right_column_name} >= parent.#{quoted_right_column_name}))"
Chris@1296 125 ).count == 0
Chris@1296 126 end
Chris@1296 127
Chris@1296 128 def no_duplicates_for_columns?
Chris@1296 129 scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
Chris@1296 130 connection.quote_column_name(c)
Chris@1296 131 end.push(nil).join(", ")
Chris@1296 132 [quoted_left_column_name, quoted_right_column_name].all? do |column|
Chris@1296 133 # No duplicates
Chris@1296 134 select("#{scope_string}#{column}, COUNT(#{column})").
Chris@1296 135 group("#{scope_string}#{column}").
Chris@1296 136 having("COUNT(#{column}) > 1").
Chris@1296 137 first.nil?
Chris@1296 138 end
Chris@1296 139 end
Chris@1296 140
Chris@1296 141 # Wrapper for each_root_valid? that can deal with scope.
Chris@1296 142 def all_roots_valid?
Chris@1296 143 if acts_as_nested_set_options[:scope]
Chris@1296 144 roots.group(scope_column_names).group_by{|record| scope_column_names.collect{|col| record.send(col.to_sym)}}.all? do |scope, grouped_roots|
Chris@1296 145 each_root_valid?(grouped_roots)
Chris@1296 146 end
Chris@1296 147 else
Chris@1296 148 each_root_valid?(roots)
Chris@1296 149 end
Chris@1296 150 end
Chris@1296 151
Chris@1296 152 def each_root_valid?(roots_to_validate)
Chris@1296 153 left = right = 0
Chris@1296 154 roots_to_validate.all? do |root|
Chris@1296 155 (root.left > left && root.right > right).tap do
Chris@1296 156 left = root.left
Chris@1296 157 right = root.right
Chris@1296 158 end
Chris@1296 159 end
Chris@1296 160 end
Chris@1296 161
Chris@1296 162 # Rebuilds the left & rights if unset or invalid.
Chris@1296 163 # Also very useful for converting from acts_as_tree.
Chris@1296 164 def rebuild!(validate_nodes = true)
Chris@1296 165 # Don't rebuild a valid tree.
Chris@1296 166 return true if valid?
Chris@1296 167
Chris@1296 168 scope = lambda{|node|}
Chris@1296 169 if acts_as_nested_set_options[:scope]
Chris@1296 170 scope = lambda{|node|
Chris@1296 171 scope_column_names.inject(""){|str, column_name|
Chris@1296 172 str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
Chris@1296 173 }
Chris@1296 174 }
Chris@1296 175 end
Chris@1296 176 indices = {}
Chris@1296 177
Chris@1296 178 set_left_and_rights = lambda do |node|
Chris@1296 179 # set left
Chris@1296 180 node[left_column_name] = indices[scope.call(node)] += 1
Chris@1296 181 # find
Chris@1296 182 where(["#{quoted_parent_column_name} = ? #{scope.call(node)}", node]).order(acts_as_nested_set_options[:order]).each{|n| set_left_and_rights.call(n) }
Chris@1296 183 # set right
Chris@1296 184 node[right_column_name] = indices[scope.call(node)] += 1
Chris@1296 185 node.save!(:validate => validate_nodes)
Chris@1296 186 end
Chris@1296 187
Chris@1296 188 # Find root node(s)
Chris@1296 189 root_nodes = where("#{quoted_parent_column_name} IS NULL").order(acts_as_nested_set_options[:order]).each do |root_node|
Chris@1296 190 # setup index for this scope
Chris@1296 191 indices[scope.call(root_node)] ||= 0
Chris@1296 192 set_left_and_rights.call(root_node)
Chris@1296 193 end
Chris@1296 194 end
Chris@1296 195
Chris@1296 196 # Iterates over tree elements and determines the current level in the tree.
Chris@1296 197 # Only accepts default ordering, odering by an other column than lft
Chris@1296 198 # does not work. This method is much more efficent than calling level
Chris@1296 199 # because it doesn't require any additional database queries.
Chris@1296 200 #
Chris@1296 201 # Example:
Chris@1296 202 # Category.each_with_level(Category.root.self_and_descendants) do |o, level|
Chris@1296 203 #
Chris@1296 204 def each_with_level(objects)
Chris@1296 205 path = [nil]
Chris@1296 206 objects.each do |o|
Chris@1296 207 if o.parent_id != path.last
Chris@1296 208 # we are on a new level, did we decent or ascent?
Chris@1296 209 if path.include?(o.parent_id)
Chris@1296 210 # remove wrong wrong tailing paths elements
Chris@1296 211 path.pop while path.last != o.parent_id
Chris@1296 212 else
Chris@1296 213 path << o.parent_id
Chris@1296 214 end
Chris@1296 215 end
Chris@1296 216 yield(o, path.length - 1)
Chris@1296 217 end
Chris@1296 218 end
Chris@1296 219 end
Chris@1296 220
Chris@1296 221 # 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@1296 222 #
Chris@1296 223 # category.self_and_descendants.count
Chris@1296 224 # category.ancestors.find(:all, :conditions => "name like '%foo%'")
Chris@1296 225
Chris@1296 226 # Value of the parent column
Chris@1296 227 def parent_id
Chris@1296 228 self[parent_column_name]
Chris@1296 229 end
Chris@1296 230
Chris@1296 231 # Value of the left column
Chris@1296 232 def left
Chris@1296 233 self[left_column_name]
Chris@1296 234 end
Chris@1296 235
Chris@1296 236 # Value of the right column
Chris@1296 237 def right
Chris@1296 238 self[right_column_name]
Chris@1296 239 end
Chris@1296 240
Chris@1296 241 # Returns true if this is a root node.
Chris@1296 242 def root?
Chris@1296 243 parent_id.nil?
Chris@1296 244 end
Chris@1296 245
Chris@1296 246 def leaf?
Chris@1296 247 new_record? || (right - left == 1)
Chris@1296 248 end
Chris@1296 249
Chris@1296 250 # Returns true is this is a child node
Chris@1296 251 def child?
Chris@1296 252 !parent_id.nil?
Chris@1296 253 end
Chris@1296 254
Chris@1296 255 # Returns root
Chris@1296 256 def root
Chris@1296 257 self_and_ancestors.where(parent_column_name => nil).first
Chris@1296 258 end
Chris@1296 259
Chris@1296 260 # Returns the array of all parents and self
Chris@1296 261 def self_and_ancestors
Chris@1296 262 nested_set_scope.where([
Chris@1296 263 "#{self.class.quoted_table_name}.#{quoted_left_column_name} <= ? AND #{self.class.quoted_table_name}.#{quoted_right_column_name} >= ?", left, right
Chris@1296 264 ])
Chris@1296 265 end
Chris@1296 266
Chris@1296 267 # Returns an array of all parents
Chris@1296 268 def ancestors
Chris@1296 269 without_self self_and_ancestors
Chris@1296 270 end
Chris@1296 271
Chris@1296 272 # Returns the array of all children of the parent, including self
Chris@1296 273 def self_and_siblings
Chris@1296 274 nested_set_scope.where(parent_column_name => parent_id)
Chris@1296 275 end
Chris@1296 276
Chris@1296 277 # Returns the array of all children of the parent, except self
Chris@1296 278 def siblings
Chris@1296 279 without_self self_and_siblings
Chris@1296 280 end
Chris@1296 281
Chris@1296 282 # Returns a set of all of its nested children which do not have children
Chris@1296 283 def leaves
Chris@1296 284 descendants.where("#{self.class.quoted_table_name}.#{quoted_right_column_name} - #{self.class.quoted_table_name}.#{quoted_left_column_name} = 1")
Chris@1296 285 end
Chris@1296 286
Chris@1296 287 # Returns the level of this object in the tree
Chris@1296 288 # root level is 0
Chris@1296 289 def level
Chris@1296 290 parent_id.nil? ? 0 : ancestors.count
Chris@1296 291 end
Chris@1296 292
Chris@1296 293 # Returns a set of itself and all of its nested children
Chris@1296 294 def self_and_descendants
Chris@1296 295 nested_set_scope.where([
Chris@1296 296 "#{self.class.quoted_table_name}.#{quoted_left_column_name} >= ? AND #{self.class.quoted_table_name}.#{quoted_right_column_name} <= ?", left, right
Chris@1296 297 ])
Chris@1296 298 end
Chris@1296 299
Chris@1296 300 # Returns a set of all of its children and nested children
Chris@1296 301 def descendants
Chris@1296 302 without_self self_and_descendants
Chris@1296 303 end
Chris@1296 304
Chris@1296 305 def is_descendant_of?(other)
Chris@1296 306 other.left < self.left && self.left < other.right && same_scope?(other)
Chris@1296 307 end
Chris@1296 308
Chris@1296 309 def is_or_is_descendant_of?(other)
Chris@1296 310 other.left <= self.left && self.left < other.right && same_scope?(other)
Chris@1296 311 end
Chris@1296 312
Chris@1296 313 def is_ancestor_of?(other)
Chris@1296 314 self.left < other.left && other.left < self.right && same_scope?(other)
Chris@1296 315 end
Chris@1296 316
Chris@1296 317 def is_or_is_ancestor_of?(other)
Chris@1296 318 self.left <= other.left && other.left < self.right && same_scope?(other)
Chris@1296 319 end
Chris@1296 320
Chris@1296 321 # Check if other model is in the same scope
Chris@1296 322 def same_scope?(other)
Chris@1296 323 Array(acts_as_nested_set_options[:scope]).all? do |attr|
Chris@1296 324 self.send(attr) == other.send(attr)
Chris@1296 325 end
Chris@1296 326 end
Chris@1296 327
Chris@1296 328 # Find the first sibling to the left
Chris@1296 329 def left_sibling
Chris@1296 330 siblings.where(["#{self.class.quoted_table_name}.#{quoted_left_column_name} < ?", left]).
Chris@1296 331 order("#{self.class.quoted_table_name}.#{quoted_left_column_name} DESC").last
Chris@1296 332 end
Chris@1296 333
Chris@1296 334 # Find the first sibling to the right
Chris@1296 335 def right_sibling
Chris@1296 336 siblings.where(["#{self.class.quoted_table_name}.#{quoted_left_column_name} > ?", left]).first
Chris@1296 337 end
Chris@1296 338
Chris@1296 339 # Shorthand method for finding the left sibling and moving to the left of it.
Chris@1296 340 def move_left
Chris@1296 341 move_to_left_of left_sibling
Chris@1296 342 end
Chris@1296 343
Chris@1296 344 # Shorthand method for finding the right sibling and moving to the right of it.
Chris@1296 345 def move_right
Chris@1296 346 move_to_right_of right_sibling
Chris@1296 347 end
Chris@1296 348
Chris@1296 349 # Move the node to the left of another node (you can pass id only)
Chris@1296 350 def move_to_left_of(node)
Chris@1296 351 move_to node, :left
Chris@1296 352 end
Chris@1296 353
Chris@1296 354 # Move the node to the left of another node (you can pass id only)
Chris@1296 355 def move_to_right_of(node)
Chris@1296 356 move_to node, :right
Chris@1296 357 end
Chris@1296 358
Chris@1296 359 # Move the node to the child of another node (you can pass id only)
Chris@1296 360 def move_to_child_of(node)
Chris@1296 361 move_to node, :child
Chris@1296 362 end
Chris@1296 363
Chris@1296 364 # Move the node to root nodes
Chris@1296 365 def move_to_root
Chris@1296 366 move_to nil, :root
Chris@1296 367 end
Chris@1296 368
Chris@1296 369 def move_possible?(target)
Chris@1296 370 self != target && # Can't target self
Chris@1296 371 same_scope?(target) && # can't be in different scopes
Chris@1296 372 # !(left..right).include?(target.left..target.right) # this needs tested more
Chris@1296 373 # detect impossible move
Chris@1296 374 !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))
Chris@1296 375 end
Chris@1296 376
Chris@1296 377 def to_text
Chris@1296 378 self_and_descendants.map do |node|
Chris@1296 379 "#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})"
Chris@1296 380 end.join("\n")
Chris@1296 381 end
Chris@1296 382
Chris@1296 383 protected
Chris@1296 384
Chris@1296 385 def without_self(scope)
Chris@1296 386 scope.where(["#{self.class.quoted_table_name}.#{self.class.primary_key} != ?", self])
Chris@1296 387 end
Chris@1296 388
Chris@1296 389 # All nested set queries should use this nested_set_scope, which performs finds on
Chris@1296 390 # the base ActiveRecord class, using the :scope declared in the acts_as_nested_set
Chris@1296 391 # declaration.
Chris@1296 392 def nested_set_scope(options = {})
Chris@1296 393 options = {:order => "#{self.class.quoted_table_name}.#{quoted_left_column_name}"}.merge(options)
Chris@1296 394 scopes = Array(acts_as_nested_set_options[:scope])
Chris@1296 395 options[:conditions] = scopes.inject({}) do |conditions,attr|
Chris@1296 396 conditions.merge attr => self[attr]
Chris@1296 397 end unless scopes.empty?
Chris@1296 398 self.class.base_class.scoped options
Chris@1296 399 end
Chris@1296 400
Chris@1296 401 def store_new_parent
Chris@1296 402 @move_to_new_parent_id = send("#{parent_column_name}_changed?") ? parent_id : false
Chris@1296 403 true # force callback to return true
Chris@1296 404 end
Chris@1296 405
Chris@1296 406 def move_to_new_parent
Chris@1296 407 if @move_to_new_parent_id.nil?
Chris@1296 408 move_to_root
Chris@1296 409 elsif @move_to_new_parent_id
Chris@1296 410 move_to_child_of(@move_to_new_parent_id)
Chris@1296 411 end
Chris@1296 412 end
Chris@1296 413
Chris@1296 414 # on creation, set automatically lft and rgt to the end of the tree
Chris@1296 415 def set_default_left_and_right
Chris@1296 416 highest_right_row = nested_set_scope(:order => "#{quoted_right_column_name} desc").find(:first, :limit => 1,:lock => true )
Chris@1296 417 maxright = highest_right_row ? (highest_right_row[right_column_name] || 0) : 0
Chris@1296 418 # adds the new node to the right of all existing nodes
Chris@1296 419 self[left_column_name] = maxright + 1
Chris@1296 420 self[right_column_name] = maxright + 2
Chris@1296 421 end
Chris@1296 422
Chris@1296 423 def in_tenacious_transaction(&block)
Chris@1296 424 retry_count = 0
Chris@1296 425 begin
Chris@1296 426 transaction(&block)
Chris@1296 427 rescue ActiveRecord::StatementInvalid => error
Chris@1296 428 raise unless connection.open_transactions.zero?
Chris@1296 429 raise unless error.message =~ /Deadlock found when trying to get lock|Lock wait timeout exceeded/
Chris@1296 430 raise unless retry_count < 10
Chris@1296 431 retry_count += 1
Chris@1296 432 logger.info "Deadlock detected on retry #{retry_count}, restarting transaction"
Chris@1296 433 sleep(rand(retry_count)*0.1) # Aloha protocol
Chris@1296 434 retry
Chris@1296 435 end
Chris@1296 436 end
Chris@1296 437
Chris@1296 438 # Prunes a branch off of the tree, shifting all of the elements on the right
Chris@1296 439 # back to the left so the counts still work.
Chris@1296 440 def destroy_descendants
Chris@1296 441 return if right.nil? || left.nil? || skip_before_destroy
Chris@1296 442
Chris@1296 443 in_tenacious_transaction do
Chris@1296 444 reload_nested_set
Chris@1296 445 # select the rows in the model that extend past the deletion point and apply a lock
Chris@1296 446 self.class.base_class.find(:all,
Chris@1296 447 :select => "id",
Chris@1296 448 :conditions => ["#{quoted_left_column_name} >= ?", left],
Chris@1296 449 :lock => true
Chris@1296 450 )
Chris@1296 451
Chris@1296 452 if acts_as_nested_set_options[:dependent] == :destroy
Chris@1296 453 descendants.each do |model|
Chris@1296 454 model.skip_before_destroy = true
Chris@1296 455 model.destroy
Chris@1296 456 end
Chris@1296 457 else
Chris@1296 458 nested_set_scope.delete_all(
Chris@1296 459 ["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?",
Chris@1296 460 left, right]
Chris@1296 461 )
Chris@1296 462 end
Chris@1296 463
Chris@1296 464 # update lefts and rights for remaining nodes
Chris@1296 465 diff = right - left + 1
Chris@1296 466 nested_set_scope.update_all(
Chris@1296 467 ["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff],
Chris@1296 468 ["#{quoted_left_column_name} > ?", right]
Chris@1296 469 )
Chris@1296 470 nested_set_scope.update_all(
Chris@1296 471 ["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff],
Chris@1296 472 ["#{quoted_right_column_name} > ?", right]
Chris@1296 473 )
Chris@1296 474
Chris@1296 475 reload
Chris@1296 476 # Don't allow multiple calls to destroy to corrupt the set
Chris@1296 477 self.skip_before_destroy = true
Chris@1296 478 end
Chris@1296 479 end
Chris@1296 480
Chris@1296 481 # reload left, right, and parent
Chris@1296 482 def reload_nested_set
Chris@1296 483 reload(
Chris@1296 484 :select => "#{quoted_left_column_name}, #{quoted_right_column_name}, #{quoted_parent_column_name}",
Chris@1296 485 :lock => true
Chris@1296 486 )
Chris@1296 487 end
Chris@1296 488
Chris@1296 489 def move_to(target, position)
Chris@1296 490 raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record?
Chris@1296 491 run_callbacks :move do
Chris@1296 492 in_tenacious_transaction do
Chris@1296 493 if target.is_a? self.class.base_class
Chris@1296 494 target.reload_nested_set
Chris@1296 495 elsif position != :root
Chris@1296 496 # load object if node is not an object
Chris@1296 497 target = nested_set_scope.find(target)
Chris@1296 498 end
Chris@1296 499 self.reload_nested_set
Chris@1296 500
Chris@1296 501 unless position == :root || move_possible?(target)
Chris@1296 502 raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree."
Chris@1296 503 end
Chris@1296 504
Chris@1296 505 bound = case position
Chris@1296 506 when :child; target[right_column_name]
Chris@1296 507 when :left; target[left_column_name]
Chris@1296 508 when :right; target[right_column_name] + 1
Chris@1296 509 when :root; 1
Chris@1296 510 else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)."
Chris@1296 511 end
Chris@1296 512
Chris@1296 513 if bound > self[right_column_name]
Chris@1296 514 bound = bound - 1
Chris@1296 515 other_bound = self[right_column_name] + 1
Chris@1296 516 else
Chris@1296 517 other_bound = self[left_column_name] - 1
Chris@1296 518 end
Chris@1296 519
Chris@1296 520 # there would be no change
Chris@1296 521 return if bound == self[right_column_name] || bound == self[left_column_name]
Chris@1296 522
Chris@1296 523 # we have defined the boundaries of two non-overlapping intervals,
Chris@1296 524 # so sorting puts both the intervals and their boundaries in order
Chris@1296 525 a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort
Chris@1296 526
Chris@1296 527 # select the rows in the model between a and d, and apply a lock
Chris@1296 528 self.class.base_class.select('id').lock(true).where(
Chris@1296 529 ["#{quoted_left_column_name} >= :a and #{quoted_right_column_name} <= :d", {:a => a, :d => d}]
Chris@1296 530 )
Chris@1296 531
Chris@1296 532 new_parent = case position
Chris@1296 533 when :child; target.id
Chris@1296 534 when :root; nil
Chris@1296 535 else target[parent_column_name]
Chris@1296 536 end
Chris@1296 537
Chris@1296 538 self.nested_set_scope.update_all([
Chris@1296 539 "#{quoted_left_column_name} = CASE " +
Chris@1296 540 "WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
Chris@1296 541 "THEN #{quoted_left_column_name} + :d - :b " +
Chris@1296 542 "WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
Chris@1296 543 "THEN #{quoted_left_column_name} + :a - :c " +
Chris@1296 544 "ELSE #{quoted_left_column_name} END, " +
Chris@1296 545 "#{quoted_right_column_name} = CASE " +
Chris@1296 546 "WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
Chris@1296 547 "THEN #{quoted_right_column_name} + :d - :b " +
Chris@1296 548 "WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
Chris@1296 549 "THEN #{quoted_right_column_name} + :a - :c " +
Chris@1296 550 "ELSE #{quoted_right_column_name} END, " +
Chris@1296 551 "#{quoted_parent_column_name} = CASE " +
Chris@1296 552 "WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
Chris@1296 553 "ELSE #{quoted_parent_column_name} END",
Chris@1296 554 {:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent}
Chris@1296 555 ])
Chris@1296 556 end
Chris@1296 557 target.reload_nested_set if target
Chris@1296 558 self.reload_nested_set
Chris@1296 559 end
Chris@1296 560 end
Chris@1296 561
Chris@1296 562 end
Chris@1296 563
Chris@1296 564 # Mixed into both classes and instances to provide easy access to the column names
Chris@1296 565 module Columns
Chris@1296 566 def left_column_name
Chris@1296 567 acts_as_nested_set_options[:left_column]
Chris@1296 568 end
Chris@1296 569
Chris@1296 570 def right_column_name
Chris@1296 571 acts_as_nested_set_options[:right_column]
Chris@1296 572 end
Chris@1296 573
Chris@1296 574 def parent_column_name
Chris@1296 575 acts_as_nested_set_options[:parent_column]
Chris@1296 576 end
Chris@1296 577
Chris@1296 578 def scope_column_names
Chris@1296 579 Array(acts_as_nested_set_options[:scope])
Chris@1296 580 end
Chris@1296 581
Chris@1296 582 def quoted_left_column_name
Chris@1296 583 connection.quote_column_name(left_column_name)
Chris@1296 584 end
Chris@1296 585
Chris@1296 586 def quoted_right_column_name
Chris@1296 587 connection.quote_column_name(right_column_name)
Chris@1296 588 end
Chris@1296 589
Chris@1296 590 def quoted_parent_column_name
Chris@1296 591 connection.quote_column_name(parent_column_name)
Chris@1296 592 end
Chris@1296 593
Chris@1296 594 def quoted_scope_column_names
Chris@1296 595 scope_column_names.collect {|column_name| connection.quote_column_name(column_name) }
Chris@1296 596 end
Chris@1296 597 end
Chris@1296 598
Chris@1296 599 end
Chris@1296 600 end
Chris@1296 601 end