how to override gem generator template in Rails app

≯℡__Kan透↙ 提交于 2019-12-22 18:47:37

问题


I know how to override a Rails template in a gem, but how can I override gem generator template in a Rails application

e.g.: https://github.com/elabs/pundit/blob/master/lib/generators/pundit/policy/templates/policy.rb

or

https://github.com/drapergem/draper/blob/master/lib/generators/rails/templates/decorator.rb

so that rails g decorator Foo would generate my template, not the gem native one

thx


回答1:


From Rails guide on generators:

In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is lib/templates.

So, if you mimic the directory hierarchy of the gem/tamplate you are trying to override, rails will pick your template instead of the ones in the gem source

Update:

Now, the question is how to correctly mimic that hierarchy so rails pick your template up?

Well it turned out there is some kind of a rule | pattern for that, for example if you want to override a template in this path: lib/generators/pundit/policy/templates/policy.rb

You should place your template in lib/templates/pundit/policy/policy.rb

To override lib/generators/rails/templates/decorator.rb

You should place your template in lib/templates/rails/decorator/decorator.rb

Update 2

It seems that the pattern is flowing: lib/templates/gem_name/generator_name/template_file_name.rb

In case of Draper gem, the gem is enforcing itself to act like native Rails generator:

/draper/lib/generators/rails/templates/decorator.rb

...so that's why we needed to use:

lib/templates/rails/generator_name/template_file_name.rb.

To override RSpec template generator of a Draper gem: lib/templates/rspec/generator_name/template_file_name.rb

...and so on




回答2:


To customize templates for twitter-bootswatch-rails gem's views generator, copy the whole content of its template folder into

lib/templates/bootswatch/themed

And run rails g bootswatch:themed YourModels




回答3:


To copy the default Pundit generators to your Rails project, you can use this command:

mkdir -p lib/templates/pundit/policy && \
cp $(bundle show pundit)/lib/generators/pundit/policy/templates/* lib/templates/pundit/policy


来源:https://stackoverflow.com/questions/21732373/how-to-override-gem-generator-template-in-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!