ruby-on-rails-5 - 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
但我不知道该怎么做。
解决方案
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
推荐阅读
- android - 在 C 中运行 Android SU 命令
- ios - 我们可以使用单个证书发布多少个应用程序以及如何同时更新所有应用程序
- xamarin - 此客户已存在具有该路由号码和帐号的银行账户 Plaid+Stripe 例外
- r - Image not displayed in row of flextable on export ppt
- python - 有没有一种方法可以计算镜像时相同的最长子字符串或子列表
- microsoft-graph-api - OnBehalfOfProfider 的工作示例,用于调用 MS Graph 的守护程序应用程序
- python - 如何将同一周的所有数字加到一个列表中?
- firebase - 在 Android 中安全地访问 Firebase 数据库
- indexing - Solr 搜索查询模式更改
- mysql - node.js mysql连接连接挂起30+秒