Class: Mistri::Workspace::Directory

Inherits:
Object
  • Object
show all
Defined in:
lib/mistri/workspace/directory.rb

Overview

Documents as files under one root. Every path resolves inside the root or raises, so a model-supplied "../../etc/passwd" cannot escape.

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Directory

Returns a new instance of Directory.



10
11
12
13
# File 'lib/mistri/workspace/directory.rb', line 10

def initialize(root)
  @root = File.expand_path(root)
  FileUtils.mkdir_p(@root)
end

Instance Method Details

#delete(path) ⇒ Object



27
28
29
30
31
# File 'lib/mistri/workspace/directory.rb', line 27

def delete(path)
  full = resolve(path)
  FileUtils.rm_f(full)
  nil
end

#list(prefix = nil) ⇒ Object



33
34
35
36
37
38
# File 'lib/mistri/workspace/directory.rb', line 33

def list(prefix = nil)
  base = @root.length + 1
  paths = Dir.glob(File.join(@root, "**", "*")).select { |f| File.file?(f) }
                                               .map { |f| f[base..] }.sort
  prefix ? paths.select { |p| p.start_with?(prefix.to_s) } : paths
end

#read(path) ⇒ Object



15
16
17
18
# File 'lib/mistri/workspace/directory.rb', line 15

def read(path)
  full = resolve(path)
  File.exist?(full) ? File.read(full) : nil
end

#write(path, content) ⇒ Object



20
21
22
23
24
25
# File 'lib/mistri/workspace/directory.rb', line 20

def write(path, content)
  full = resolve(path)
  FileUtils.mkdir_p(File.dirname(full))
  File.write(full, content.to_s)
  nil
end