Created
July 23, 2012 17:26
-
-
Save IdahoEv/3164868 to your computer and use it in GitHub Desktop.
Crappy code to emit a menu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Submission to the Cascadia ruby ticket giveaway: https://codeclimate.com/cascadiaruby. | |
# | |
# We have a Location model used to model a heirarchical menu tree with acts_as_awesome_nested_set, | |
# so the client can edit his nav menu. This horrific beast is what outputs the menu, generating | |
# a zillion database hits in the process. NOTE: all this effort is for a menu that typically has | |
# all of ten items in it. | |
## app/views/shared/_location_subtree.html.haml | |
%li{ :class => matches_current_path?(location) ? "current" : nil } | |
= link_to(location.name.titleize, loc_path(location)) | |
- unless children.empty? | |
%ul | |
- children.each do |child| | |
=child | |
## app/helpers/application_helper.rb | |
# 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.html_safe | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment