简体   繁体   English

如何在使用 Rails Mailer Preview 时保持干净的开发数据库

[英]How to keep a clean development DB while using Rails Mailer Preview

If you are like me, your development Rails BD is for fudging some data.如果你像我一样,你的 Rails BD 开发是为了捏造一些数据。 Even if not everything is perfect like my production database, I try to not insert so much junk data so I can at least control my development expectations.即使不是一切都像我的生产数据库一样完美,我尽量不插入这么多垃圾数据,这样我至少可以控制我的开发期望。

By using FactoryBot or plain RoR you can create in memory object and run the very nice ActionMailer::Preview tool in the development version of RoR.通过使用 FactoryBot 或普通 RoR,您可以在 memory object 中创建并在 RoR 的开发版本中运行非常好的 ActionMailer::Preview 工具。 This will save you tons of time if you have to adjust HTML and CSS.如果您必须调整 HTML 和 CSS,这将为您节省大量时间。

But what about a view that require a BD access?但是需要 BD 访问权限的视图呢? This happen to me as I need a table to present some user information from the database.这发生在我身上,因为我需要一个表格来显示数据库中的一些用户信息。

If you use create or FactoryBot.create you'll end up with a lot of records in your BD that you don't really need.如果您使用 create 或 FactoryBot.create,您最终会在 BD 中得到很多您并不真正需要的记录。

The question then is how to manage a cleanup of the data after the previewer run?那么问题是如何在预览器运行后管理数据清理?

Based on suggestion of my friend, he comes up with the idea of a around filter that look like this.根据我朋友的建议,他想出了一个看起来像这样的环绕过滤器的想法。

class UserMailerPreview < ActionMailer::Preview

  def welcome_email
    around_email do
      UserMailer.with(user: user).welcome
    end
  end

  private 

  def user 
    @user ||= FactoryBot.create(:user)
  end 

  def around_email
    message = nil
    begin
      ActiveRecord::Base.transaction do 
        message = yield 
        message.to_s # This force the evaluation of the message body instead of the lasy render
        raise ActiveRecord::Rollback
      end
    rescue ActiveRecord::Rollback
    end
    message
  end
end

This cute trick will create all the data you need, render the email body and clean the database.这个可爱的技巧将创建您需要的所有数据,渲染 email 主体并清理数据库。 So you can create as much junk you need for your email without having a burden on your personnal work.因此,您可以为您的 email 创建尽可能多的垃圾,而不会对您的个人工作造成负担。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM