我有一个看起来像这样的基本自定义生成器,它继承自Rails 5.1应用程序中的Rails :: Generators :: NamedBase
class NotificationGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def notification
copy_file "notification.rb", "app/notifications/#{file_name}.rb"
copy_file "notification_spec.rb", "spec/notifications/#{file_name}_spec.rb"
end
end
我的模板文件名为notification.rb.tt,它位于../templates目录下。
模板看起来像这样:
class <%= class_name %> < Notification
def to_mail
end
def to_sms
end
end
但是,当我运行生成器时,创建的文件在文件中具有<%= class_name%>,而不是该方法调用的结果。如何使生成器实际呈现为erb模板?
在深入研究了一些Rails核心提交后,我发现this issue讨论了文件扩展。
好像在rails 5.2中,所有模板都被重命名为.tt(这意味着如果我升级,上面的代码可能会工作,我没有深入到rails core)。
然而,作为我在5.1上个人使用的修复,rafaelfranca的最后评论揭示了一个解决方案。如果我使用'template'而不是copy_file,它会正确地解析和输出。
工作生成器看起来像这样:
class NotificationGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def notification
template "notification.rb", "app/notifications/#{file_name}.rb"
template "notification_spec.rb", "spec/notifications/#{file_name}_spec.rb"
end
end