Search code examples
ruby-on-railsrubyfileutils

Create new directory in parent directory of current directory -- ROR FileUtils.mkdir


This is my basic hierarchy ... MYPROJECTS/MYRAILSAPP/source_code_folders

  • I have a folder MYPROJECTS that holds my ror applications

  • My application source code is held in a folder called MYRAILSAPP which is within MYPROJECTS

  • Source code is in subdirectories within MYRAILSAPP

I use FileUtils.mkdir in MYRAILSAPP/app/controllers/files_controller.rb

class FilesController < ApplicationController
    layout 'files'
  def home
  end
  def index
    if File.exist?('new')

    else
      files = Dir.glob('*')
      FileUtils.mkdir 'new'
      FileUtils.cp_r files, 'new'
    end
  end
end

This creates a new directory in MYRAILSAPP so it is MYRAILSAPP/new

I am wanting to create the new directory so it is MYPROJECTS/new


Solution

  • To define that directory as a Pathname:

    path = Rails.root.join('..', 'new')
    

    To create it on disk:

    path.mkpath
    

    To check if it already exists:

    path.exist?
    

    See the Pathname documentation for more things you can do.