If you are like me, your development Rails BD is for fudging some data. 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. This will save you tons of time if you have to adjust HTML and CSS.
But what about a view that require a BD access ? 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.
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. So you can create as much junk you need for your email without having a burden on your personnal work.