Create a file in the specified directory

How to create a new file in a specific directory. I created this class:

class FileManager

    def initialize()

    end

    def createFile(name,extension)
        return File.new(name <<"."<<extension, "w+")
    end
end

I would like to indicate the directory (path) where you can create the file. If this does not exist, it will be created. So what should I use fileutils, as shown here immediately after creating the file, or can I indicate directly in the creation of the place where the file will be created?

thank

+5
source share
1 answer

The following code checks to see if there is a directory in which you went through (pulling the directory out of the path with File.dirname) and creating it if it is not. Then it creates the file as before.

require 'fileutils'

def create_file(path, extension)
  dir = File.dirname(path)

  unless File.directory?(dir)
    FileUtils.mkdir_p(dir)
  end

  path << ".#{extension}"
  File.new(path, 'w')
end
+25
source

All Articles