如何更改自定义rails生成器的源? (雷神)

我正在制作一个自定义生成器,生成一个新的rails应用程序,我这样做

require 'thor' require 'rails/generators/rails/app/app_generator' class AppBuilder < Rails::AppBuilder include Thor::Actions include Thor::Shell ... end 

问题是,如何添加新的源目录(然后由Thor::Actions#copy_fileThor::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

这些点是必需的,因为ruby文件'app_builder.rb'被填满并且在rails new命令变为新的app目录之后eval'd(我认为)。