2

我有一个看起来像这样的基本自定义生成器,它继承自 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 模板一样实际渲染?

4

1 回答 1

1

在挖掘了一些 Rails 核心提交后,我发现这个问题有点讨论文件扩展名。

似乎在 rails 5.2 中所有模板都重命名为 .tt (这意味着如果我要升级上面的代码可能会工作,我没有深入到 rails 核心)。

然而,作为我个人在 5.1 上使用的修复,rafaelfranca 的最后一条评论揭示了一个解决方案。如果我使用“模板”而不是 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
于 2019-03-19T04:10:35.933 回答