How to override a rails generator template in a gem?

后端 未结 6 1092
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 07:18

When you want to override a generator template (without replacing the generator itself), in Rails 3 you can just drop files in appropriately named places in lib/templates and Ra

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 07:48

    I have the same problem using rails 4.1.5. And here is assembled puzzle solution.

    First of all create Railtie in your gem like this. Keep in mind config.generators is deprecated and thalespf`s answer.

    module SomeGem
      class Railtie < Rails::Railtie
        config.app_generators do |g|
          g.templates.unshift File::expand_path('../../templates', __FILE__)
        end
      end
    end
    

    Works like a charm!

    UPD. I have tried to create a gem with templates only and use it within Rails::Engine. But it requires this:

    # lib/your_engine/engine.rb
    require 'your_gem_with_generator_templates' # Loads Railtie
    

提交回复
热议问题