Method: File::Utils#create

Defined in:
lib/file/utils.rb

#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