Skip to content
Browse files

Add ClassMethods#root + spec

Add before create and before destroy hooks
  • Loading branch information...
1 parent 30c2049 commit cf58aad7c165df87325444eb325c80399684a3ca Paweł Kondzior committed Jan 8, 2009
Showing with 49 additions and 2 deletions.
  1. +1 −0 TODO
  2. +42 −0 lib/sequel_nested_set.rb
  3. +6 −2 spec/nested_set_spec.rb
View
1 TODO
@@ -1,3 +1,4 @@
- Add configuration options
- Add move, rebuild! and integration check methods, and specs for methods + full code covarage
- Do more specs for scoped nested_set
+- Add move hooks (before_,after_)
View
42 lib/sequel_nested_set.rb
@@ -55,6 +55,9 @@ def self.apply(model, options = {})
attr_accessor :nested_set_options
end
model.nested_set_options = options
+
+ model.before_create { set_default_left_and_right }
+ model.before_destroy { prune_from_tree }
end
module DatasetMethods
@@ -77,6 +80,12 @@ def leaves
end
module ClassMethods
+
+ # Returns the first root
+ def root
+ roots.first
+ end
+
def qualified_parent_column
"#{self.implicit_table_name}__#{self.nested_set_options[:parent_column]}".to_sym
end
@@ -259,6 +268,39 @@ def set_default_left_and_right
self.left = maxright + 1
self.right = 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 self.right.nil? || self.left.nil?
+ diff = self.right - self.left + 1
+
+ #TODO: implemente :dependent option
+# delete_method = acts_as_nested_set_options[:dependent] == :destroy ?
+# :destroy_all : :delete_all
+
+ #TODO: implement prune method
+# 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
end
end
end
View
8 spec/nested_set_spec.rb
@@ -34,8 +34,8 @@
roots.should == Client.filter(:parent_id => nil).all
roots.should == [@root, @root2]
end
-
- it "should have root that will be root? => true" do
+
+ it "should have root that will be root? => true" do
Client.roots.first.root?.should be_true
end
@@ -44,6 +44,10 @@
leaves.should == Client.nested.filter(:rgt - :lft => 1).all
leaves.should == [@node1, @node2_1, @node3, @root2]
end
+
+ it "should have root" do
+ Client.root.should == @root
+ end
end
describe "Sequel Nested Set Instance" do

0 comments on commit cf58aad

Please sign in to comment.
Something went wrong with that request. Please try again.