如何复制*的目录.有托尔的文件吗?



是否可以复制一个目录*。Tt文件而不执行模板引擎。我想改进我的rails模板和添加自定义脚手架模板(视图,控制器和规格),但每次我使用directory方法

directory "lib/templates", force: true

当作者试图为这些文件启动模板引擎时,我看到一个异常。如何复制我的目录吗?

我认为最简单和最安全的选择是glob和copy_file,如@engineersmnky所描述的。

但是,有一种方法使用directory而不执行模板。唯一的障碍是这个常量:

TEMPLATE_EXTNAME = ".tt"

通常情况下,你不应该改变常量,但它要求它不被冻结。最坏的情况是什么tm:

# test.thor
class Test < Thor
include Thor::Actions
def self.source_root = __dir__
desc "example", "task"
def example
ignore_tt do
directory "templates", "copy"           # <= ok
end
# directory_with_tt "templates", "copy"   # <= ok
# directory         "templates", "copy"   # <= fail
end
private
def ignore_tt
# NOTE: change template extension so it would skip
#       `when /#{TEMPLATE_EXTNAME}$/` condition and
#        fallback to default `copy_file`
Thor::TEMPLATE_EXTNAME.concat "_no_match" # => .tt_no_match
yield
ensure
# NOTE: make sure to undo our dirty work after the block
Thor::TEMPLATE_EXTNAME.chomp! "_no_match" # => .tt
end
def directory_with_tt(...)
ignore_tt do
directory(...)
end
end
end

和一个小测试:

$ cat templates/*.tt
class <%= name.capitalize %>
end
$ thor test:example
create  copy
create  copy/file.tt
$ cat copy/*.tt
class <%= name.capitalize %>
end

如果上面的方法太粗糙,这里有另一个,并不像我想象的那么简单,只需要得到source_rootdestination_root的权利。

class Test < Thor
include Thor::Actions
def self.source_root = "#{__dir__}/templates"
argument :name
desc "example", "task"
def example
# copy directory, skip .tt
directory ".", "copy", exclude_pattern: /.tt$/
# copy .tt
Pathname.new(self.class.source_root).glob("**/*.tt").each do |tt|
copy_file tt, File.join("copy", tt.relative_path_from(self.class.source_root))
end
# # this works too
# self.destination_root = "copy"
# Pathname.new(self.class.source_root).glob("**/*.tt").each do |tt|
#   copy_file tt.relative_path_from(self.class.source_root)
# end
end
end
# %name% and .empty_directory are handled by `directory`
# file.tt is copied with `copy_file`
templates
├── %name%.rb
├── empty
│  └── .empty_directory
└── tt
└── file.tt
$ thor test:example app_name
create  copy
create  copy/app_name.rb
create  copy/empty
create  copy/tt/file.tt

最新更新