[英]How to change source for a custom rails generator? (Thor)
我正在制作一个生成新 Rails 应用程序的自定义生成器,我这样做
require 'thor'
require 'rails/generators/rails/app/app_generator'
class AppBuilder < Rails::AppBuilder
include Thor::Actions
include Thor::Shell
...
end
问题是,我如何添加一个新的源目录(然后由Thor::Actions#copy_file
、 Thor::Actions#template
和其他人使用)? 我在 Thor 的文档中看到Thor::Actions#source_paths
保存源(它是一个路径数组),所以我尝试在我的类中覆盖它(因为我已经包含了Thor::Actions
):
def source_paths
[File.join(File.expand_path(File.dirname(__FILE__)), "templates")] + super
end
有了这个,我想在源代码中添加./templates
目录,同时仍然保留 Rails 的目录(这就是为什么最后加上+ super
的原因)。 但是它不起作用,它仍然将Rails的源路径列为唯一的。
我尝试浏览 Rails 的源代码,但我找不到 Rails 如何将他的目录放在源路径中。 我真的很想知道:)
这有效:
require 'thor'
require 'rails/generators/rails/app/app_generator'
module Thor::Actions
def source_paths
[MY_TEMPLATES]
end
end
class AppBuilder < Rails::AppBuilder
...
end
我不明白为什么,但我已经花了太多时间在这上面,所以我不在乎。
Thor 将访问您的 source_paths 方法并将这些添加到默认值中:
# Returns the source paths in the following order:
#
# 1) This class source paths
# 2) Source root
# 3) Parents source paths
#
def source_paths_for_search
paths = []
paths += self.source_paths
paths << self.source_root if self.source_root
paths += from_superclass(:source_paths, [])
paths
end
所以你在课堂上需要做的就是:
class NewgemGenerator < Thor::Group
include Thor::Actions
def source_paths
['/whatever', './templates']
end
end
希望这可以帮助 :)
使用 AppBuilder 时 source_paths 方法不起作用。 (这是使用 rails 模板的另一种选择)。 我在这个类所在的 app_builder.rb 文件旁边有一个文件目录。我有这个工作,但似乎仍然应该有一个更优雅的方式。
tree .
|-- app_builder.rb
|-- files
`-- Gemfile
class AppBuilder < Rails::AppBuilder
def initialize generator
super generator
path = File.expand_path( File.join( '..', File.dirname( __FILE__ )) )
source_paths << path
end
def gemfile
copy_file 'files/Gemfile', 'Gemfile'
end
然后在控制台上:
rails new my_app -b path_to_app_builder.rb
这些点是必需的,因为在rails new
命令更改为新的应用程序目录(我认为)之后,ruby 文件“app_builder.rb”被删除并评估。
这是一个旧帖子,但是,问题仍然存在,我花了一些时间来解决这个问题。 如果有帮助,我在这里发表评论。
Rails 默认添加路径lib/templates
因此您可以通过将它们复制到此目录中来自定义任何模板。
查看正确的目录结构https://github.com/rails/rails/tree/v6.0.1/railties/lib/rails/generators/rails
虽然有微妙之处,但不是很明显。
以helper
生成器为例,Rails 官方文档中提到,其结构为
https://github.com/rails/rails/tree/v6.0.1/railties/lib/rails/generators/rails/helper
- helper
- templates
- helper.rb.tt
- helper_generator.rb
在这里, Railties
希望在您的项目中找到的内容:
- lib
- templates
- helper
- helper.rb
您helper.rb
是副本helper.rb.tt
最后一件事,如果你打算在Rails::Engine
使用它,你必须告诉它加载那个路径
# lib/blorgh/engine.rb
module Blorgh
class Engine < ::Rails::Engine
isolate_namespace Blorgh
config.generators.templates << File.expand_path('../templates', __dir__)
end
end
真心希望能帮到别人,节省时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.