Module: File::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
lib/file/utils.rb

Instance Method Summary collapse

Instance Method Details

#create(path, &block) ⇒ Object

Creates a file. If you provide a block, the method will yield the created file, opened for writing.

Without a block

File::Utils.create '/my/file/rb'

With a block

File::Utils.create '/my/file.rb' do |f|
  f.write "some code here" 
end

Raises

Errno::EEXIST:: if the file already exists


20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/file/utils.rb', line 20

def create(path, &block)
  if File.file?(path)
    raise Errno::EEXIST, path
  end
  
  FileUtils.mkdir_p(File.dirname(path))
  FileUtils.touch(path)
  
  if block_given?
    begin yield file = File.open(path, 'w')
    ensure file.close
    end
  end
end

#destroy(*paths) ⇒ Object

File::Utils.remove ‘/my/file.asp’ File::Utils.remove Dir



37
38
39
40
41
# File 'lib/file/utils.rb', line 37

def destroy(*paths)
  paths.each do |path|
    FileUtils.rm(path) if File.file?(path)        
  end
end

#destroy!(*paths) ⇒ Object

Acts like remove, but doesn’t check whether files exist before attempting to remove them.

Raises

Errno::ENOENT:: if a file you're trying to delete doesn't exist.


48
49
50
51
52
# File 'lib/file/utils.rb', line 48

def destroy!(*paths)
  paths.each do |path|
    FileUtils.rm(path)
  end
end

#rewrite(path, contents) ⇒ Object

Opens a file, overwrite its contents with the contents you provide, then closes the file.



56
57
58
# File 'lib/file/utils.rb', line 56

def rewrite(path, contents)
  File.open(path, 'w') { |f| f.write(contents) }
end