Created
April 11, 2013 18:52
-
-
Save mje113/5366123 to your computer and use it in GitHub Desktop.
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
def self.tree(path = nil) | |
Rails.cache.fetch("folder-tree-#{path}", expires_in: 0) do | |
folders = Folder.where('path LIKE ?', "#{path}%").all | |
path_parts = path.to_s.count('/') | |
local_root = root | |
local_first_tier = [] | |
folders.each do |folder| | |
folder.children = folders.select { |f| f.parent_id == folder.id }.sort { |a, b| a.position <=> b.position } | |
local_root = folder if path == folder.path | |
local_first_tier << folder if folder.path.count('/') == path_parts | |
end | |
local_root.children = local_first_tier if local_root.root? | |
local_root | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment