Skip to content

Instantly share code, notes, and snippets.

@mje113
Created April 11, 2013 18:52
Show Gist options
  • Save mje113/5366123 to your computer and use it in GitHub Desktop.
Save mje113/5366123 to your computer and use it in GitHub Desktop.
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