Created
February 11, 2016 03:56
-
-
Save deep-spaced/c00f6551e0c35011dbe9 to your computer and use it in GitHub Desktop.
Optimized version of my super-fancy tree generator.
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
module TreeGeneratorOptimized | |
def self.generate_tree | |
pages = all.select('id, name, depth, parent_id, sort_order').order('sort_order ASC') | |
ordered_pages = ActiveSupport::OrderedHash.new | |
parent_hash = Hash.new | |
pages.each do |page| | |
parent_hash[page.parent_id] = Array.new if parent_hash[page.parent_id].nil? | |
parent_hash[page.parent_id].push(page) unless page.nil? | |
end | |
pages.each do |page| | |
ordered_pages[page.id] = {page: page, children: generate_children_optimized(page, parent_hash)} if page.depth == 0 | |
end | |
ordered_pages | |
end | |
protected | |
def self.generate_children_optimized(page, page_hash) | |
children = ActiveSupport::OrderedHash.new | |
if page_hash.has_key?(page.id) | |
page_hash[page.id].each {|p| children[p.id] = {page: p, children: generate_children_optimized(p, page_hash)} } | |
end | |
children | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment