Module: EvenBetterNestedSet::NestedSet::ClassMethods

Defined in:
lib/eb_nested_set.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#nested_set_optionsObject

Returns the value of attribute nested_set_options.



20
21
22
# File 'lib/eb_nested_set.rb', line 20

def nested_set_options
  @nested_set_options
end

Instance Method Details

#find_boundaries(id) ⇒ Object



26
27
28
29
30
31
# File 'lib/eb_nested_set.rb', line 26

def find_boundaries(id)
  query = "SELECT #{nested_set_column(:left)}, #{nested_set_column(:right)}" +
          "FROM #{quote_db_property(table_name)}" +
          "WHERE #{quote_db_property(primary_key)} = #{id}"
  connection.select_rows(query).first
end

#find_last_rootObject



22
23
24
# File 'lib/eb_nested_set.rb', line 22

def find_last_root
  find(:first, :order => "#{nested_set_column(:right)} DESC", :conditions => { :parent_id => nil })
end

#find_with_nested_set(*args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/eb_nested_set.rb', line 37

def find_with_nested_set(*args)
  result = find(*args)
  if result.respond_to?(:cache_nested_set)
    result.cache_nested_set
  elsif result.respond_to?(:each)
    result.each do |node|
      node.cache_nested_set
    end
  end
  result
end

#nested_setObject



33
34
35
# File 'lib/eb_nested_set.rb', line 33

def nested_set
  sort_nodes_to_nested_set(find(:all, :order => "#{nested_set_column(:left)} ASC"))
end

#nested_set_column(name) ⇒ Object



72
73
74
# File 'lib/eb_nested_set.rb', line 72

def nested_set_column(name)
  quote_db_property(nested_set_options[name])
end

#quote_db_property(property) ⇒ Object



86
87
88
# File 'lib/eb_nested_set.rb', line 86

def quote_db_property(property)
  "`#{property}`".gsub('.','`.`')
end

#recalculate_nested_setObject

Recalculates the left and right values for the entire tree



77
78
79
80
81
82
83
84
# File 'lib/eb_nested_set.rb', line 77

def recalculate_nested_set
  transaction do
    left = 1
    roots.each do |root|
      left = root.recalculate_nested_set(left)
    end
  end
end

#sort_nodes_to_nested_set(nodes) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/eb_nested_set.rb', line 49

def sort_nodes_to_nested_set(nodes)
  roots = []
  hashmap = {}
  for node in nodes.sort_by { |n| n.left }
    # if the parent is not in the hashmap, parent will be nil, therefore node will be a root node
    # in that case
    parent = node.parent_id ? hashmap[node.parent_id] : nil
    
    # make sure this is called at least once on every node, so leaves know that they have *no* children
    node.cache_children()

    if parent
      node.cache_parent(parent)
      parent.cache_children(node)
    else
      roots << node
    end

    hashmap[node.id] = node
  end
  return roots
end