Class: FileSandbox::Sandbox

Inherits:
Object
  • Object
show all
Includes:
Test::Unit::Assertions
Defined in:
lib/file_sandbox.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = '__sandbox') ⇒ Sandbox

Returns a new instance of Sandbox.



52
53
54
55
56
# File 'lib/file_sandbox.rb', line 52

def initialize(path = '__sandbox')
  @root = File.expand_path(path)
  clean_up
  FileUtils.mkdir_p @root
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



50
51
52
# File 'lib/file_sandbox.rb', line 50

def root
  @root
end

Instance Method Details

#[](name) ⇒ Object



58
59
60
# File 'lib/file_sandbox.rb', line 58

def [](name)
  SandboxFile.new(File.join(@root, name))
end

#assert(options) ⇒ Object

usage assert :file=>‘my file.rb’, :has_contents=>‘some stuff’



87
88
89
90
91
92
93
94
# File 'lib/file_sandbox.rb', line 87

def assert(options)
  name = File.join(@root, options[:file])
  if (expected_content = options[:has_content] || options[:has_contents])
    assert_equal(expected_content, File.read(name))
  else
    fail('expected something to assert')
  end
end

#clean_upObject



96
97
98
99
100
101
# File 'lib/file_sandbox.rb', line 96

def clean_up
  FileUtils.rm_rf @root
  if File.exists? @root
    raise "Could not remove directory #{@root.inspect}, something is probably still holding a lock on it"
  end
end

#new(options) ⇒ Object

usage new :file=>‘my file.rb’, :with_contents=>‘some stuff’



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/file_sandbox.rb', line 63

def new(options)
  if options.has_key? :directory
    dir = self[options.delete(:directory)]
    FileUtils.mkdir_p dir.path
  else
    file = self[options.delete(:file)]
    if (binary_content = options.delete(:with_binary_content) || options.delete(:with_binary_contents))
      file.binary_content = binary_content
    else
      file.content = (options.delete(:with_content) || options.delete(:with_contents) || '')
    end
  end
  
  raise "unexpected keys '#{options.keys.join(', ')}'" unless options.empty?
  
  dir || file
end

#remove(options) ⇒ Object



81
82
83
84
# File 'lib/file_sandbox.rb', line 81

def remove(options)
  name = File.join(@root, options[:file])
  FileUtils.remove_file name
end