如何在Rails应用程序中覆盖gem生成器模板
我知道如何覆盖gem中的Rails模板,但是如何在Rails应用程序中覆盖gem生成器模板
例如: https : //github.com/elabs/pundit/blob/master/lib/generators/pundit/policy/templates/policy.rb
要么
https://github.com/drapergem/draper/blob/master/lib/generators/rails/templates/decorator.rb
所以rails g decorator Foo
会生成我的模板,而不是gem本机模板
谢谢
从Rails指南发电机 :
在Rails 3.0及更高版本中,生成器不仅在源根目录中查找模板,还在其他路径中搜索模板。 其中一个是lib / templates。
因此,如果您模仿要尝试覆盖的gem / tamplate的目录层次结构,rails将选择您的模板而不是gem源中的模板
更新:
现在,问题是如何正确模仿该层次结构,以便rails选择您的模板?
事实certificate,有一种规则| 模式,例如,如果要覆盖此路径中的模板: lib/generators/pundit/policy/templates/policy.rb
您应该将模板放在lib/templates/pundit/policy/policy.rb
重写lib/generators/rails/templates/decorator.rb
您应该将模板放在lib/templates/rails/decorator/decorator.rb
更新2
似乎模式正在流动: lib/templates/gem_name/generator_name/template_file_name.rb
在Draper gem的情况下,gem会强制自己像本机Rails生成器一样:
/draper/lib/generators/rails/templates/decorator.rb
……这就是我们需要使用的原因:
lib/templates/rails/generator_name/template_file_name.rb
。
要覆盖Draper gem的RSpec模板生成器: lib/templates/rspec/generator_name/template_file_name.rb
…等等
要为twitter-bootswatch-rails gem的视图生成器自定义模板, 请将 其模板文件夹的全部内容复制到其中
lib/templates/bootswatch/themed
并运行rails g bootswatch:themed YourModels
要将默认Pundit生成器复制到Rails项目,可以使用以下命令:
mkdir -p lib/templates/pundit/policy && \ cp $(bundle show pundit)/lib/generators/pundit/policy/templates/* lib/templates/pundit/policy