Module: TheSortableTreeHelper

Defined in:
app/helpers/the_sortable_tree_helper.rb

Instance Method Summary collapse

Instance Method Details

#define_class_of_elements_of(tree) ⇒ Object

sortable_tree @pages, :new_url => new_page_url, :max_levels => 5

sortable_tree @products, :new_url => new_product_url, :path => ‘products/the_sortable_tree’

sortable_tree @catalogs, :namespace => :admin, :new_url => new_catalog_url, :max_levels => 5



12
13
14
15
16
17
18
# File 'app/helpers/the_sortable_tree_helper.rb', line 12

def define_class_of_elements_of tree
  case
    #when tree.is_a?(ActiveRecord::Relation) then tree.name.to_s.downcase
    when tree.empty? then nil
    else tree.first.class.to_s.underscore
  end
end

#sortable_tree(tree, opts = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'app/helpers/the_sortable_tree_helper.rb', line 20

def sortable_tree(tree, opts= {})
  opts.merge!({
    :path  => opts[:path] || :the_sortable_tree,
    :klass => define_class_of_elements_of(tree),
    :title => opts[:title] || :title,
    :max_levels => opts[:max_levels] || 3,
    :namespace => Array.wrap(opts[:namespace])
  })
  render :partial => "#{opts[:path]}/tree", :locals => { :tree => sortable_tree_builder(tree, opts), :opts => opts }
end

#sortable_tree_builder(tree, options = {}) ⇒ Object



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 'app/helpers/the_sortable_tree_helper.rb', line 31

def sortable_tree_builder(tree, options= {})
  result = ''
  opts = {
    :id => :id,           # node id field
    :node => nil,         # node
    :root => false,       # is it root node?
    :level => 0           # recursion level
  }.merge!(options)

  root = opts[:root]
  node = opts[:node]

  unless node
    roots = tree.select{ |elem| elem.parent_id.nil? }

    # TODO: try to remove compact
    # children rendering
    if roots.empty? && !tree.empty?
      min_parent_id = tree.map(&:parent_id).compact.min
      roots = tree.select{ |elem| elem.parent_id == min_parent_id }
    end

    roots.each do |root|
      _opts  =  opts.merge({:node => root, :root => true, :level => opts[:level].next})
      result << sortable_tree_builder(tree, _opts)
    end
  else
    children_res = ''
    children = tree.select{|elem| elem.parent_id == node.id}
    opts.merge!({:has_children => children.blank?})
    children.each do |elem|
      _opts        =  opts.merge({:node => elem, :root => false, :level => opts[:level].next})
      children_res << sortable_tree_builder(tree, _opts)
    end
    result << render(:partial => "#{opts[:path]}/node", :locals => {:opts => opts, :root => root, :node => node, :children => children_res})
  end
  raw result
end