Module: MptTree

Defined in:
lib/mpt_tree.rb,
lib/mpt_tree/engine.rb,
lib/mpt_tree/version.rb,
app/models/mpt_tree/node.rb,
app/helpers/mpt_tree/application_helper.rb,
app/controllers/mpt_tree/application_controller.rb

Defined Under Namespace

Modules: ApplicationHelper Classes: ApplicationController, Engine, Node

Constant Summary collapse

VERSION =
"0.0.7"

Instance Method Summary collapse

Instance Method Details

#acts_as_treeObject



5
6
7
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mpt_tree.rb', line 5

def acts_as_tree
  has_one :mpt_tree_node, :as=>:tree, :dependent=>:destroy, :class_name=>"MptTree::Node"
  default_scope lambda {joins(:mpt_tree_node).order('mpt_tree_nodes.lft')}

  class_eval do 
    def make_it_root
      create_mpt_tree_node #unless MptTree::Node.root_created? self.class.name
      self.reload
    end

    def tree
      node_ids = mpt_tree_node.tree
      self.class.name.constantize.where(:id => node_ids)
    end

    def insert(node)
      raise "can not be inserted! node already have parent." if node.mpt_tree_node
      mpt_tree_node.insert(node)
    end

    def parent
      ancestors.last
    end
    
    def siblings
      parent.nodes_at_level(level(parent)) - [self]
    end

    def children
      nodes_at_level(1)
    end
    
    def self.root
      name.constantize.first
    end

    def root?
       (level(self.class.name.constantize.first) == 0) ? true : false
    end

    def leaf?
      !children.present?
    end

    def ancestors
      node_ids = mpt_tree_node.ancestors
      self.class.name.constantize.where(:id => node_ids)
    end

    def self_with_ancestors
      ancestors << self
    end

    def level(parent=nil)
      mpt_tree_node.level(parent)
    end

    def nodes_at_level(level)
      nodes = Array.new
      tree.each do |node|
        nodes << node if node.level(self) == level
      end
      nodes
    end

    def change_parent(node)
      mpt_tree_node.destroy
      self.reload
      node.insert(self)
    end

    alias_method :<<, :insert
  end
end