How to change source for a custom rails generator? (Thor)

后端 未结 4 1939
遥遥无期
遥遥无期 2020-12-21 15:18

I\'m making a custom generator that generates a new rails app, and I do it like this

require \'thor\'
require \'rails/generators/rails/app/app_generator\'

c         


        
4条回答
  •  春和景丽
    2020-12-21 15:45

    It's an old post, however, the problem remains the same, I spent time to figure that out. I let a comment here if it can help.

    Rails add by default the path lib/templates so you can custom any templates by copying them in this directory.

    Check out the correct directories structures https://github.com/rails/rails/tree/v6.0.1/railties/lib/rails/generators/rails

    There is subtle though and is not so obvious to catch.

    Take for instance the helper generator, as mentioned in the official Rails documentation, the structure is

    https://github.com/rails/rails/tree/v6.0.1/railties/lib/rails/generators/rails/helper

    - helper
      - templates
        - helper.rb.tt
      - helper_generator.rb 
    

    Here, what Railties expects to find in your project:

    - lib
      - templates 
        - helper
          - helper.rb
    

    your helper.rb is a copy of helper.rb.tt

    the last thing, if you plan to use it in Rails::Engine you have to tell it to load that path

    # lib/blorgh/engine.rb 
    module Blorgh
      class Engine < ::Rails::Engine
        isolate_namespace Blorgh
        config.generators.templates << File.expand_path('../templates', __dir__)
      end
    end
    

    Really hope that can help and save time for others.

    1. https://github.com/rails/rails/blob/v6.0.1/railties/lib/rails/application/configuration.rb#L188
    2. https://guides.rubyonrails.org/generators.html#customizing-your-workflow-by-changing-generators-templates
    3. https://github.com/rails/rails/blob/v6.0.1/railties/CHANGELOG.md
    4. https://guides.rubyonrails.org/engines.html

提交回复
热议问题