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.



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

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.



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

def root
  @root
end

Instance Method Details

#[](name) ⇒ Object



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

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

#assert(options) ⇒ Object

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



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

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



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

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’



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

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



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

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