Rails 5: How to add folders and files in application template script

Viewed 586

I would like to add folders and add files (like my own readme.md) to newly created rails apps using application templates.

In template.rb

require "fileutils"
require "shellwords"

def add_folders
  mkdir views/components/buttons
  mkdir csv/
end

def add_file
  cd csv
  touch user.csv
end

def add_readme
   rm README.md
   touch README.md
   inject_into_file("README.md", "New readme..")
end

after_bundle do
  add_folder
  add_file
  add_readme
end

But I don't know how to do it.

1 Answers

FileUtils covers most of what you want. mkdir_p uses the command line mkdir -p command, which makes the full path if the directories don't exist.

IO.write (which File inherits from IO) accepts a file name, and content. No need to delete the old file and touch a new one.

Also, you'll want to make sure you use Rails.root.join with your file paths. It's similar to File.join, in that it helps you build a file path without doubling up your / on accident, but it also returns an absolute file path on your computer. Also, it makes your code OS agnostic because while unix systems use '/' as the folder separator, Windows computers use '\'. So, Rails.root.join makes all of that safer.

Here's an example of using it on a unix system:

If Rails.root is '/some/cool/path/here', then Rails.root.join('views','components', 'buttons') would be '/some/cool/path/here/views/components/buttons'.

require 'fileutils'
require 'shellwords'

def add_folders
  FileUtils.mkdir_p(Rails.root.join('views', 'components', 'buttons'))
  FileUtils.mkdir_p(Rails.root.join('csv'))
end

def add_file
  FileUtils.touch('Rails.root.join('csv', 'user.csv'))
end

def add_readme
   File.write(Rails.root.join('README.md'), 'New readme..')
end

after_bundle do
  add_folder
  add_file
  add_readme
end
Related