2

I have a Ruby on Rails application with multiple environments (development, staging, production). In my staging environment, I want to be able to override all emails being sent from the system to go to the current_user logged in. Everything I've read is telling me I have to keep passing in current_user into my mailer. However, this doesn't seem logical for me as there are hundreds of mailer code to change.

What I'd ideally like to do is to setup an email intercepter, override the mail.to and always send to current_user. Is there a way to do this? Here's what I have so far in my intializers:

if Rails.env.staging?
 class OverrideMailRecipient
   def self.delivering_email(mail)
     mail.to = ['development@xxx.com']
   end
 end
 ActionMailer::Base.register_interceptor(OverrideMailRecipient)
end

This works, but now I'd like to make it so it goes to current user instead of a hard-coded email.

As a bonus, I'd like add to the body of the email the original recipients of the email, so the current user knows who was supposed to receive it in production.

I hope this makes sense, any help is appreciated! :)

I'm using Rails 5.1.4 and Devise for authentication.

Sixers17
  • 592
  • 2
  • 5
  • 20

1 Answers1

0

The only way I see is to add the current user to some global variable, then you would be able to access it from the Interceptor. Here is an option: https://stackoverflow.com/a/2513456/740394

To add any information you want to the mailers, use a partial with a condition in your layout like you did for the interceptor.

render('sender_info') if Rails.env.staging?
Rodrigo
  • 5,435
  • 5
  • 42
  • 78
  • How do you mean as a global variable? Since the interceptor loads during boot as an initializer, how do you set current_user at that point? – Sixers17 Nov 01 '18 at 17:53