How to override a rails generator template in a gem?

后端 未结 6 1093
爱一瞬间的悲伤
爱一瞬间的悲伤 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:42

    We figured this out. the generators config has a 'templates' variable that lists search paths for templates. The problem is indeed that it searches this array in order until it finds a match, so templates in your app or in Rails will get found before templates in your gem.

    The solution is to have your gem's Railtie put the templates path onto the beginning of the array of template paths. It looks like this. This file is in [GEM]/lib/my_gem.rb. The templates are parallel to it in [GEM]/lib/templates/.

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

    If the templates have a path inside [GEM]/lib/templates that matches the path of the default template you are overriding, this should work. For example, if you've done this and you create [GEM]/lib/templates/active_record/model/model.rb, it will override the default AR model template.

    No monkeypatching of the generators required.

    EDIT: Note that since this answer was originally posted, "config.generators" has been removed from Rails. Use config.app_generators instead as per pixelearth's answer below.

提交回复
热议问题