To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / .svn / pristine / 3e / 3e2856705bc7c004aa221bf2a7acea9b1ba0b99e.svn-base @ 1297:0a574315af3e

History | View | Annotate | Download (21.4 KB)

1
module CollectiveIdea #:nodoc:
2
  module Acts #:nodoc:
3
    module NestedSet #:nodoc:
4
      def self.included(base)
5
        base.extend(SingletonMethods)
6
      end
7

    
8
      # This acts provides Nested Set functionality. Nested Set is a smart way to implement
9
      # an _ordered_ tree, with the added feature that you can select the children and all of their
10
      # descendants with a single query. The drawback is that insertion or move need some complex
11
      # sql queries. But everything is done here by this module!
12
      #
13
      # Nested sets are appropriate each time you want either an orderd tree (menus,
14
      # commercial categories) or an efficient way of querying big trees (threaded posts).
15
      #
16
      # == API
17
      #
18
      # Methods names are aligned with acts_as_tree as much as possible, to make replacment from one
19
      # by another easier, except for the creation:
20
      #
21
      # in acts_as_tree:
22
      #   item.children.create(:name => "child1")
23
      #
24
      # in acts_as_nested_set:
25
      #   # adds a new item at the "end" of the tree, i.e. with child.left = max(tree.right)+1
26
      #   child = MyClass.new(:name => "child1")
27
      #   child.save
28
      #   # now move the item to its right place
29
      #   child.move_to_child_of my_item
30
      #
31
      # You can pass an id or an object to:
32
      # * <tt>#move_to_child_of</tt>
33
      # * <tt>#move_to_right_of</tt>
34
      # * <tt>#move_to_left_of</tt>
35
      #
36
      module SingletonMethods
37
        # Configuration options are:
38
        #
39
        # * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id)
40
        # * +:left_column+ - column name for left boundry data, default "lft"
41
        # * +:right_column+ - column name for right boundry data, default "rgt"
42
        # * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id"
43
        #   (if it hasn't been already) and use that as the foreign key restriction. You
44
        #   can also pass an array to scope by multiple attributes.
45
        #   Example: <tt>acts_as_nested_set :scope => [:notable_id, :notable_type]</tt>
46
        # * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the
47
        #   child objects are destroyed alongside this object by calling their destroy
48
        #   method. If set to :delete_all (default), all the child objects are deleted
49
        #   without calling their destroy method.
50
        #
51
        # See CollectiveIdea::Acts::NestedSet::ClassMethods for a list of class methods and
52
        # CollectiveIdea::Acts::NestedSet::InstanceMethods for a list of instance methods added 
53
        # to acts_as_nested_set models
54
        def acts_as_nested_set(options = {})
55
          options = {
56
            :parent_column => 'parent_id',
57
            :left_column => 'lft',
58
            :right_column => 'rgt',
59
            :order => 'id',
60
            :dependent => :delete_all, # or :destroy
61
          }.merge(options)
62
          
63
          if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/
64
            options[:scope] = "#{options[:scope]}_id".intern
65
          end
66

    
67
          write_inheritable_attribute :acts_as_nested_set_options, options
68
          class_inheritable_reader :acts_as_nested_set_options
69
          
70
          include Comparable
71
          include Columns
72
          include InstanceMethods
73
          extend Columns
74
          extend ClassMethods
75

    
76
          # no bulk assignment
77
          attr_protected  left_column_name.intern,
78
                          right_column_name.intern, 
79
                          parent_column_name.intern
80
                          
81
          before_create :set_default_left_and_right
82
          before_destroy :prune_from_tree
83
                          
84
          # no assignment to structure fields
85
          [left_column_name, right_column_name, parent_column_name].each do |column|
86
            module_eval <<-"end_eval", __FILE__, __LINE__
87
              def #{column}=(x)
88
                raise ActiveRecord::ActiveRecordError, "Unauthorized assignment to #{column}: it's an internal field handled by acts_as_nested_set code, use move_to_* methods instead."
89
              end
90
            end_eval
91
          end
92
          
93
          named_scope :roots, :conditions => {parent_column_name => nil}, :order => quoted_left_column_name
94
          named_scope :leaves, :conditions => "#{quoted_right_column_name} - #{quoted_left_column_name} = 1", :order => quoted_left_column_name
95
          if self.respond_to?(:define_callbacks)
96
            define_callbacks("before_move", "after_move")              
97
          end
98

    
99
          
100
        end
101
        
102
      end
103
      
104
      module ClassMethods
105
        
106
        # Returns the first root
107
        def root
108
          roots.find(:first)
109
        end
110
        
111
        def valid?
112
          left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
113
        end
114
        
115
        def left_and_rights_valid?
116
          count(
117
            :joins => "LEFT OUTER JOIN #{quoted_table_name} AS parent ON " +
118
              "#{quoted_table_name}.#{quoted_parent_column_name} = parent.#{primary_key}",
119
            :conditions =>
120
              "#{quoted_table_name}.#{quoted_left_column_name} IS NULL OR " +
121
              "#{quoted_table_name}.#{quoted_right_column_name} IS NULL OR " +
122
              "#{quoted_table_name}.#{quoted_left_column_name} >= " +
123
                "#{quoted_table_name}.#{quoted_right_column_name} OR " +
124
              "(#{quoted_table_name}.#{quoted_parent_column_name} IS NOT NULL AND " +
125
                "(#{quoted_table_name}.#{quoted_left_column_name} <= parent.#{quoted_left_column_name} OR " +
126
                "#{quoted_table_name}.#{quoted_right_column_name} >= parent.#{quoted_right_column_name}))"
127
          ) == 0
128
        end
129
        
130
        def no_duplicates_for_columns?
131
          scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
132
            connection.quote_column_name(c)
133
          end.push(nil).join(", ")
134
          [quoted_left_column_name, quoted_right_column_name].all? do |column|
135
            # No duplicates
136
            find(:first, 
137
              :select => "#{scope_string}#{column}, COUNT(#{column})", 
138
              :group => "#{scope_string}#{column} 
139
                HAVING COUNT(#{column}) > 1").nil?
140
          end
141
        end
142
        
143
        # Wrapper for each_root_valid? that can deal with scope.
144
        def all_roots_valid?
145
          if acts_as_nested_set_options[:scope]
146
            roots(:group => scope_column_names).group_by{|record| scope_column_names.collect{|col| record.send(col.to_sym)}}.all? do |scope, grouped_roots|
147
              each_root_valid?(grouped_roots)
148
            end
149
          else
150
            each_root_valid?(roots)
151
          end
152
        end
153
        
154
        def each_root_valid?(roots_to_validate)
155
          left = right = 0
156
          roots_to_validate.all? do |root|
157
            (root.left > left && root.right > right).tap do
158
              left = root.left
159
              right = root.right
160
            end
161
          end
162
        end
163
                
164
        # Rebuilds the left & rights if unset or invalid.  Also very useful for converting from acts_as_tree.
165
        def rebuild!(force=false)
166
          # Don't rebuild a valid tree.
167
          # valid? doesn't strictly validate the tree
168
          return true if !force && valid?
169
          
170
          scope = lambda{|node|}
171
          if acts_as_nested_set_options[:scope]
172
            scope = lambda{|node| 
173
              scope_column_names.inject(""){|str, column_name|
174
                str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
175
              }
176
            }
177
          end
178
          indices = {}
179
          
180
          set_left_and_rights = lambda do |node|
181
            # set left
182
            node[left_column_name] = indices[scope.call(node)] += 1
183
            # find
184
            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) }
185
            # set right
186
            node[right_column_name] = indices[scope.call(node)] += 1    
187
            node.save!    
188
          end
189
                              
190
          # Find root node(s)
191
          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|
192
            # setup index for this scope
193
            indices[scope.call(root_node)] ||= 0
194
            set_left_and_rights.call(root_node)
195
          end
196
        end
197
      end
198
      
199
      # Mixed into both classes and instances to provide easy access to the column names
200
      module Columns
201
        def left_column_name
202
          acts_as_nested_set_options[:left_column]
203
        end
204
        
205
        def right_column_name
206
          acts_as_nested_set_options[:right_column]
207
        end
208
        
209
        def parent_column_name
210
          acts_as_nested_set_options[:parent_column]
211
        end
212
        
213
        def scope_column_names
214
          Array(acts_as_nested_set_options[:scope])
215
        end
216
        
217
        def quoted_left_column_name
218
          connection.quote_column_name(left_column_name)
219
        end
220
        
221
        def quoted_right_column_name
222
          connection.quote_column_name(right_column_name)
223
        end
224
        
225
        def quoted_parent_column_name
226
          connection.quote_column_name(parent_column_name)
227
        end
228
        
229
        def quoted_scope_column_names
230
          scope_column_names.collect {|column_name| connection.quote_column_name(column_name) }
231
        end
232
      end
233

    
234
      # 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.
235
      #
236
      #   category.self_and_descendants.count
237
      #   category.ancestors.find(:all, :conditions => "name like '%foo%'")
238
      module InstanceMethods
239
        # Value of the parent column
240
        def parent_id
241
          self[parent_column_name]
242
        end
243
        
244
        # Value of the left column
245
        def left
246
          self[left_column_name]
247
        end
248
        
249
        # Value of the right column
250
        def right
251
          self[right_column_name]
252
        end
253

    
254
        # Returns true if this is a root node.
255
        def root?
256
          parent_id.nil?
257
        end
258
        
259
        def leaf?
260
          new_record? || (right - left == 1)
261
        end
262

    
263
        # Returns true is this is a child node
264
        def child?
265
          !parent_id.nil?
266
        end
267

    
268
        # order by left column
269
        def <=>(x)
270
          left <=> x.left
271
        end
272
        
273
        # Redefine to act like active record
274
        def ==(comparison_object)
275
          comparison_object.equal?(self) ||
276
            (comparison_object.instance_of?(self.class) &&
277
              comparison_object.id == id &&
278
              !comparison_object.new_record?)
279
        end
280

    
281
        # Returns root
282
        def root
283
          self_and_ancestors.find(:first)
284
        end
285

    
286
        # Returns the immediate parent
287
        def parent
288
          nested_set_scope.find_by_id(parent_id) if parent_id
289
        end
290

    
291
        # Returns the array of all parents and self
292
        def self_and_ancestors
293
          nested_set_scope.scoped :conditions => [
294
            "#{self.class.table_name}.#{quoted_left_column_name} <= ? AND #{self.class.table_name}.#{quoted_right_column_name} >= ?", left, right
295
          ]
296
        end
297

    
298
        # Returns an array of all parents
299
        def ancestors
300
          without_self self_and_ancestors
301
        end
302

    
303
        # Returns the array of all children of the parent, including self
304
        def self_and_siblings
305
          nested_set_scope.scoped :conditions => {parent_column_name => parent_id}
306
        end
307

    
308
        # Returns the array of all children of the parent, except self
309
        def siblings
310
          without_self self_and_siblings
311
        end
312

    
313
        # Returns a set of all of its nested children which do not have children  
314
        def leaves
315
          descendants.scoped :conditions => "#{self.class.table_name}.#{quoted_right_column_name} - #{self.class.table_name}.#{quoted_left_column_name} = 1"
316
        end    
317

    
318
        # Returns the level of this object in the tree
319
        # root level is 0
320
        def level
321
          parent_id.nil? ? 0 : ancestors.count
322
        end
323

    
324
        # Returns a set of itself and all of its nested children
325
        def self_and_descendants
326
          nested_set_scope.scoped :conditions => [
327
            "#{self.class.table_name}.#{quoted_left_column_name} >= ? AND #{self.class.table_name}.#{quoted_right_column_name} <= ?", left, right
328
          ]
329
        end
330

    
331
        # Returns a set of all of its children and nested children
332
        def descendants
333
          without_self self_and_descendants
334
        end
335

    
336
        # Returns a set of only this entry's immediate children
337
        def children
338
          nested_set_scope.scoped :conditions => {parent_column_name => self}
339
        end
340

    
341
        def is_descendant_of?(other)
342
          other.left < self.left && self.left < other.right && same_scope?(other)
343
        end
344
        
345
        def is_or_is_descendant_of?(other)
346
          other.left <= self.left && self.left < other.right && same_scope?(other)
347
        end
348

    
349
        def is_ancestor_of?(other)
350
          self.left < other.left && other.left < self.right && same_scope?(other)
351
        end
352
        
353
        def is_or_is_ancestor_of?(other)
354
          self.left <= other.left && other.left < self.right && same_scope?(other)
355
        end
356
        
357
        # Check if other model is in the same scope
358
        def same_scope?(other)
359
          Array(acts_as_nested_set_options[:scope]).all? do |attr|
360
            self.send(attr) == other.send(attr)
361
          end
362
        end
363

    
364
        # Find the first sibling to the left
365
        def left_sibling
366
          siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} < ?", left],
367
            :order => "#{self.class.table_name}.#{quoted_left_column_name} DESC")
368
        end
369

    
370
        # Find the first sibling to the right
371
        def right_sibling
372
          siblings.find(:first, :conditions => ["#{self.class.table_name}.#{quoted_left_column_name} > ?", left])
373
        end
374

    
375
        # Shorthand method for finding the left sibling and moving to the left of it.
376
        def move_left
377
          move_to_left_of left_sibling
378
        end
379

    
380
        # Shorthand method for finding the right sibling and moving to the right of it.
381
        def move_right
382
          move_to_right_of right_sibling
383
        end
384

    
385
        # Move the node to the left of another node (you can pass id only)
386
        def move_to_left_of(node)
387
          move_to node, :left
388
        end
389

    
390
        # Move the node to the left of another node (you can pass id only)
391
        def move_to_right_of(node)
392
          move_to node, :right
393
        end
394

    
395
        # Move the node to the child of another node (you can pass id only)
396
        def move_to_child_of(node)
397
          move_to node, :child
398
        end
399
        
400
        # Move the node to root nodes
401
        def move_to_root
402
          move_to nil, :root
403
        end
404
        
405
        def move_possible?(target)
406
          self != target && # Can't target self
407
          same_scope?(target) && # can't be in different scopes
408
          # !(left..right).include?(target.left..target.right) # this needs tested more
409
          # detect impossible move
410
          !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))
411
        end
412
        
413
        def to_text
414
          self_and_descendants.map do |node|
415
            "#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})"
416
          end.join("\n")
417
        end
418
        
419
      protected
420
      
421
        def without_self(scope)
422
          scope.scoped :conditions => ["#{self.class.table_name}.#{self.class.primary_key} != ?", self]
423
        end
424
        
425
        # All nested set queries should use this nested_set_scope, which performs finds on
426
        # the base ActiveRecord class, using the :scope declared in the acts_as_nested_set
427
        # declaration.
428
        def nested_set_scope
429
          options = {:order => "#{self.class.table_name}.#{quoted_left_column_name}"}
430
          scopes = Array(acts_as_nested_set_options[:scope])
431
          options[:conditions] = scopes.inject({}) do |conditions,attr|
432
            conditions.merge attr => self[attr]
433
          end unless scopes.empty?
434
          self.class.base_class.scoped options
435
        end
436
        
437
        # on creation, set automatically lft and rgt to the end of the tree
438
        def set_default_left_and_right
439
          maxright = nested_set_scope.maximum(right_column_name) || 0
440
          # adds the new node to the right of all existing nodes
441
          self[left_column_name] = maxright + 1
442
          self[right_column_name] = maxright + 2
443
        end
444
      
445
        # Prunes a branch off of the tree, shifting all of the elements on the right
446
        # back to the left so the counts still work.
447
        def prune_from_tree
448
          return if right.nil? || left.nil? || !self.class.exists?(id)
449

    
450
          self.class.base_class.transaction do
451
            reload_nested_set
452
            if acts_as_nested_set_options[:dependent] == :destroy
453
              children.each(&:destroy)
454
            else
455
              nested_set_scope.send(:delete_all,
456
                ["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?",
457
                  left, right]
458
              )
459
            end
460
            reload_nested_set
461
            diff = right - left + 1
462
            nested_set_scope.update_all(
463
              ["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff],
464
              ["#{quoted_left_column_name} >= ?", right]
465
            )
466
            nested_set_scope.update_all(
467
              ["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff],
468
              ["#{quoted_right_column_name} >= ?", right]
469
            )
470
          end
471
          
472
          # Reload is needed because children may have updated their parent (self) during deletion.
473
          reload
474
        end
475

    
476
        # reload left, right, and parent
477
        def reload_nested_set
478
          reload(:select => "#{quoted_left_column_name}, " +
479
            "#{quoted_right_column_name}, #{quoted_parent_column_name}")
480
        end
481
        
482
        def move_to(target, position)
483
          raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record?
484
          return if callback(:before_move) == false
485
          transaction do
486
            if target.is_a? self.class.base_class
487
              target.reload_nested_set
488
            elsif position != :root
489
              # load object if node is not an object
490
              target = nested_set_scope.find(target)
491
            end
492
            self.reload_nested_set
493
          
494
            unless position == :root || move_possible?(target)
495
              raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree."
496
            end
497
            
498
            bound = case position
499
              when :child;  target[right_column_name]
500
              when :left;   target[left_column_name]
501
              when :right;  target[right_column_name] + 1
502
              when :root;   1
503
              else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)."
504
            end
505
          
506
            if bound > self[right_column_name]
507
              bound = bound - 1
508
              other_bound = self[right_column_name] + 1
509
            else
510
              other_bound = self[left_column_name] - 1
511
            end
512

    
513
            # there would be no change
514
            return if bound == self[right_column_name] || bound == self[left_column_name]
515
          
516
            # we have defined the boundaries of two non-overlapping intervals, 
517
            # so sorting puts both the intervals and their boundaries in order
518
            a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort
519

    
520
            new_parent = case position
521
              when :child;  target.id
522
              when :root;   nil
523
              else          target[parent_column_name]
524
            end
525

    
526
            self.class.base_class.update_all([
527
              "#{quoted_left_column_name} = CASE " +
528
                "WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
529
                  "THEN #{quoted_left_column_name} + :d - :b " +
530
                "WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
531
                  "THEN #{quoted_left_column_name} + :a - :c " +
532
                "ELSE #{quoted_left_column_name} END, " +
533
              "#{quoted_right_column_name} = CASE " +
534
                "WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
535
                  "THEN #{quoted_right_column_name} + :d - :b " +
536
                "WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
537
                  "THEN #{quoted_right_column_name} + :a - :c " +
538
                "ELSE #{quoted_right_column_name} END, " +
539
              "#{quoted_parent_column_name} = CASE " +
540
                "WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
541
                "ELSE #{quoted_parent_column_name} END",
542
              {:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent}
543
            ], nested_set_scope.proxy_options[:conditions])
544
          end
545
          target.reload_nested_set if target
546
          self.reload_nested_set
547
          callback(:after_move)
548
        end
549

    
550
      end
551
      
552
    end
553
  end
554
end