Skip to content

Instantly share code, notes, and snippets.

@onewland
Created October 3, 2010 19:53
Show Gist options
  • Save onewland/608864 to your computer and use it in GitHub Desktop.
Save onewland/608864 to your computer and use it in GitHub Desktop.
# Never Again.
def link_tree(location, options=nil)
return "" unless location
options ||= {}
max_depth = options[:max_depth] || 5
partial = options[:partial] || "shared/location_subtree"
loc_tree = []
max_depth.times do
loc_tree << {}
end
render_tree = {}
Location.each_with_level(location.descendants.all(:include => :page)) do |loc, depth|
next if depth >= max_depth
if loc_tree[depth][loc.parent_id]
loc_tree[depth][loc.parent_id] << loc
else
loc_tree[depth][loc.parent_id] = [loc]
end
end
# Find the highest depth leaves
current_depth_leaves = loc_tree.last
while loc_tree.last.empty?
current_depth_leaves = loc_tree.pop
end
current_depth_leaves = loc_tree.pop
while !current_depth_leaves.empty? && !loc_tree.empty?
current_depth_leaves.each do |parent_id, leaves|
leaves.each do |leaf|
children = render_tree[leaf.id] || []
if render_tree[parent_id]
render_tree[parent_id] << render(:partial => partial, :locals => {:location => leaf, :children => children})
else
render_tree[parent_id] = [ render(:partial => partial, :locals => {:location => leaf, :children => children}) ]
end
end
end
current_depth_leaves = loc_tree.pop
end
render_tree_root_node = render_tree[location.id]
render_tree_root_node.join
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment