Module: DataMapper::Is::NestedSet::GenerateMethod

Public Visibility

Public Instance Method Summary

#is_a_nested_set(options={})

docs in the works.

Public Instance Method Details

is_a_nested_set

public is_a_nested_set(options={})

docs in the works

[View source]


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
58
59
60
61
62
63
64
65
66
67
68
# File 'dm-more/dm-is-nested_set/lib/dm-is-nested_set/is/nested_set.rb', line 13

def is_a_nested_set(options={})
  options = { :child_key => :parent_id }.merge(options)

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

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

  belongs_to :parent,  :class_name => self.name, :child_key => [ options[:child_key] ], :order => [:lft.asc]
  has n,     :children,:class_name => self.name, :child_key => [ options[:child_key] ], :order => [:lft.asc]

  before :create do
    # scenarios:
    # - user creates a new object and does not specify a parent
    # - user creates a new object with a direct reference to a parent
    # - user spawnes a new object, and then moves it to a position
    if !self.parent





      self.class.root ? self.move_without_saving(:into => self.class.root) : self.move_without_saving(:to => 1)
      # if this is actually root, it will not move a bit (as lft is already 1)
    elsif self.parent && !self.lft
      # user has set a parent before saving (and without moving it anywhere). just move into that, and continue
      # might be som problems here if the referenced parent is not saved.
      self.move_without_saving(:into => self.parent)
    end
  end

  before :update do
    # scenarios:
    # - user moves the object to a position
    # - user has changed the parent
    # - user has removed any reference to a parent
    # - user sets the parent_id to something, and then use #move before saving
    if (self.parent && !self.lft) || (self.parent != self.ancestor)





      # if the parent is set, we try to move this into that parent, otherwise move into root.
      self.parent ? self.move_without_saving(:into => self.parent) : self.move_without_saving(:into => self.class.root)
    end
  end

  ##
  # reloads the position-attributes on all loaded objects after saving.
  #
  after :save do
    self.class.reload_positions
  end
end