首页 > 解决方案 > Rails 5:如何在应用程序模板脚本中添加文件夹和文件

问题描述

我想使用应用程序模板将文件夹和文件(如我自己的 readme.md)添加到新创建的 Rails 应用程序中。

在模板.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

但我不知道该怎么做。

标签: ruby-on-rails-5

解决方案


FileUtils 涵盖了您想要的大部分内容。mkdir_p使用命令行mkdir -p命令,如果目录不存在,则生成完整路径。

IO.write(File 继承自 IO)接受文件名和内容。无需删除旧文件并触摸新文件。

此外,您需要确保使用Rails.root.join文件路径。它类似于File.join,因为它可以帮助您构建文件路径而不会意外加倍/,但它也会返回您计算机上的绝对文件路径。此外,它使您的代码与操作系统无关,因为当 unix 系统使用“/”作为文件夹分隔符时,Windows 计算机使用“\”。所以,Rails.root.join让这一切更安全。

以下是在 unix 系统上使用它的示例:

如果 Rails.root 是'/some/cool/path/here',那么Rails.root.join('views','components', 'buttons')就是'/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

推荐阅读