equivalent8
equivalent8

Reputation: 14227

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

Upvotes: 2

Views: 1406

Answers (3)

Tim Krins
Tim Krins

Reputation: 3819

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

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

Upvotes: 0

Nimir
Nimir

Reputation: 5839

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

Upvotes: 6

Marlon Mendez
Marlon Mendez

Reputation: 83

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

Upvotes: 1

Related Questions