Class: Sandbox

Inherits:
Object
  • Object
show all
Defined in:
lib/sandbox.rb

Overview

Represents a temporary sandbox for testing that relies on the filesystem.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ Sandbox

Creates a new Sandbox with an optional path.

Parameters

path

The path to use. default: generate one in Dir.tmpdir



33
34
35
36
37
# File 'lib/sandbox.rb', line 33

def initialize(path = nil)
  self.path = path || generate_path
  
  FileUtils.mkdir_p(self.path)
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



7
8
9
# File 'lib/sandbox.rb', line 7

def path
  @path
end

Class Method Details

.play(options = {}, &block) ⇒ Object

Executes the block and yields the path to the sandbox directory. Cleans up the sandbox after the block is complete.

Options

:path

the path to use. default: generate one in Dir.tmpdir

:cd

change directory with Dir.chdir to the temp directory



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sandbox.rb', line 14

def self.play(options = {}, &block)
  sandbox = Sandbox.new(options[:path])

  begin
    if options[:cd]
      Dir.chdir(sandbox.path) do
        yield sandbox.path
      end
    else
      yield sandbox.path
    end
  ensure
    sandbox.close
  end
end

Instance Method Details

#closeObject

Cleans up the sandbox by removing the path



40
41
42
# File 'lib/sandbox.rb', line 40

def close
  FileUtils.rm_r(path)
end