class GivenFilesystem
Public Class Methods
new()
click to toggle source
# File lib/given_filesystem.rb, line 24 def initialize @path_elements = [ Dir.tmpdir, "given_filesystem" ] @base_paths = Array.new end
Public Instance Methods
cleanup()
click to toggle source
# File lib/given_filesystem.rb, line 29 def cleanup @base_paths.each do |base_path| # Better safe than sorry, so do sanity check on path before removing it if base_path =~ /given_filesystem/ FileUtils.rm_r base_path end end end
directory(user_provided_directory = nil) { || ... }
click to toggle source
# File lib/given_filesystem.rb, line 38 def directory user_provided_directory = nil create_random_base_path unless path_has_base? directory_to_create = user_provided_directory || random_name @path_elements.push directory_to_create created_path = path FileUtils.mkdir_p created_path yield if block_given? @path_elements.pop File.join path, first_segment_of_path(directory_to_create) end
directory_from_data(to, from = nil)
click to toggle source
# File lib/given_filesystem.rb, line 53 def directory_from_data to, from = nil from ||= to create_random_base_path unless path_has_base? FileUtils.mkdir_p path @path_elements.push to created_path = path FileUtils.cp_r test_data_path(from), path @path_elements.pop created_path end
file(file_name = nil, options = {})
click to toggle source
# File lib/given_filesystem.rb, line 67 def file file_name = nil, options = {} create_random_base_path unless path_has_base? if file_name @path_elements.push file_name else @path_elements.push random_name end FileUtils.mkdir_p File.dirname(path) created_path = path File.open(created_path,"w") do |file| if options[:from] test_data = test_data_path(options[:from]) if !File.exists? test_data raise "Test data file '#{test_data}' doesn't exist" end file.write File.read(test_data) else file.puts "GivenFilesystem was here" end end @path_elements.pop created_path end
Private Instance Methods
create_random_base_path()
click to toggle source
# File lib/given_filesystem.rb, line 96 def create_random_base_path @path_elements.push random_name @base_paths.push path end
first_segment_of_path(path)
click to toggle source
# File lib/given_filesystem.rb, line 117 def first_segment_of_path path path.split(File::SEPARATOR).reject(&:empty?).first end
path()
click to toggle source
# File lib/given_filesystem.rb, line 105 def path @path_elements.join("/") end
path_has_base?()
click to toggle source
# File lib/given_filesystem.rb, line 109 def path_has_base? @path_elements.count > 2 end
random_name()
click to toggle source
# File lib/given_filesystem.rb, line 101 def random_name "#{Process.pid}-#{Time.now.strftime("%Y%m%d")}-#{rand(99999).to_s}" end
test_data_path(name)
click to toggle source
# File lib/given_filesystem.rb, line 113 def test_data_path name File.expand_path('spec/data/' + name) end