Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-4rubygems

how to override gem generator template in Rails app


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


Solution

  • 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