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


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

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



39
40
41
42
43
# File 'lib/file/utils.rb', line 39

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.


50
51
52
53
54
# File 'lib/file/utils.rb', line 50

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.



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

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