Module: DataMapper::Is::NestedSet

Defined in:
lib/dm-is-nested_set/is/nested_set.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods Classes: RecursiveNestingError, UnableToPositionError

Instance Method Summary collapse

Instance Method Details

#is_nested_set(options = {}) ⇒ Object

docs in the works



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/dm-is-nested_set/is/nested_set.rb', line 8

def is_nested_set(options={})
  options = { :child_key => [ :parent_id ], :scope => [] }.merge(options)

  extend  DataMapper::Is::NestedSet::ClassMethods
  include DataMapper::Is::NestedSet::InstanceMethods

  @nested_set_scope  = options[:scope]
  @nested_set_parent = options[:child_key]

  property :lft, Integer, :writer => :private
  property :rgt, Integer, :writer => :private

  # a temporary fix. I need to filter. now I just use parent.children in self_and_siblings, which could
  # be cut down to 1 instead of 2 queries. this would be the other way, but seems hackish:
  # options[:child_key].each{|pname| property(pname, Integer) unless properties.detect{|p| p.name == pname}}

  belongs_to :parent,   :model => self, :child_key => options[:child_key], :order => [ :lft ], :required => false
  has n,     :children, :model => self, :child_key => options[:child_key], :order => [ :lft ]

  before :create do
    if !parent
      # TODO must change for nested sets
      root ? move_without_saving(:into => root) : move_without_saving(:to => 1)
    elsif parent && !lft
      move_without_saving(:into => parent)
    end
  end

  before :update do
    if nested_set_scope != original_nested_set_scope
      # TODO detach from old list first. many edge-cases here, need good testing
      self.lft, self.rgt = nil, nil
      #puts "#{root.inspect} - #{[nested_set_scope,original_nested_set_scope].inspect}"
      root ? move_without_saving(:into => root) : move_without_saving(:to => 1)
    elsif (parent && !lft) || (parent != ancestor)
      # if the parent is set, we try to move this into that parent, otherwise move into root.
      parent ? move_without_saving(:into => parent) : move_without_saving(:into => model.root)
    end
  end

  before :destroy do
    __send__(:detach)
  end

  after_class_method :inherited do |retval, target|
    target.instance_variable_set(:@nested_set_scope,  @nested_set_scope.dup)
    target.instance_variable_set(:@nested_set_parent, @nested_set_parent.dup)
  end

end