File Tree Component

Curated ago by @jeremysmithco

Description

This is a view component that renders out the file tree in the editor menu for RailsInspire.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class FileTree
  def initialize(files)
    @files = files
  end

  def tree
    files.sort_by { |file| file.path }
         .map { |file| path_hash(file.path.split("/"), file) }
         .reduce({}) { |full, path| full.deep_merge(path) }
  end

  private

  attr_reader :files

  def path_hash(fragments, file)
    if fragments.size == 1
      { fragments[0] => file }
    else
      { fragments[0] => path_hash(fragments[1..-1], file) }
    end
  end
end