构建Rails自定义模型生成器时,能否提取模板公共逻辑为局部文件?
Absolutely! You can absolutely extract reusable chunks of your generator templates into partials—this is a perfect way to eliminate repetitive code and keep your templates clean. Here’s a step-by-step breakdown of how to make this work for your custom model generator:
1. Create a Partial Template for the Reusable Code
First, create a dedicated directory for your partials (to keep things organized) and add the reusable start method as a partial file. Let’s put it in lib/generators/custom_model/templates/_partials/start_method.rb.erb:
def start puts "Vroum!" end
(Note: The leading underscore in _partials isn’t strictly required, but it’s a common convention to denote partial directories in Rails ecosystems.)
2. Update Your Main Templates to Render the Partial
Now, modify your existing model templates (like car_model.rb.erb and plane_model.rb.erb) to include the partial instead of repeating the code. Use ERB’s render method to pull in the partial:
For car_model.rb.erb:
class <%= model_name.camelcase %> < ApplicationRecord <%= render partial: 'partials/start_method' %> end
For plane_model.rb.erb (or any other model template that needs the start method):
class <%= model_name.camelcase %> < ApplicationRecord # Add plane-specific methods here <%= render partial: 'partials/start_method' %> end
3. Optional: Pass Variables to the Partial
If your partial ever needs dynamic data from the main template or generator, you can pass locals to it. For example, if you wanted to customize the output message:
Updated partial (_partials/start_method.rb.erb):
def start puts "<%= start_sound %>" end
Rendering with locals in car_model.rb.erb:
class <%= model_name.camelcase %> < ApplicationRecord <%= render partial: 'partials/start_method', locals: { start_sound: "Vroum!" } %> end
And in plane_model.rb.erb:
class <%= model_name.camelcase %> < ApplicationRecord <%= render partial: 'partials/start_method', locals: { start_sound: "Roar!" } %> end
This approach keeps your code DRY (Don’t Repeat Yourself) and makes it easy to update the reusable logic in one place instead of hunting through every template.
内容的提问来源于stack exchange,提问作者David B.

