Paritosh Singh
Paritosh Singh

Reputation: 6384

Rails:Send mail using mailer when controller finishes its execution

I am using a button for report abuse, clicking on which ajax call goes to controller and after inserting post as abused in database it is returning success. On successful response it is displaying on UI topic as abused. Now i want to send mails to admin about this. I have integrated mailer in controller, i.e. on success mailer code executes and mails are send to admin.

Now problem is that sending mails take too much time, so my ajax response time also increases. What I want is that mailer code should execute after controller sends its response, so that response time should decrease.

Thanks

Upvotes: 1

Views: 1063

Answers (3)

Carson Cole
Carson Cole

Reputation: 4451

A simple way to handle this is to create a Thread to handle the email. Simply do:

Thread.new do
  SomeMailer.some_method.deliver
end

Your controller action will continue and finish the Ajax response while the thread is separately handled. Keep in mind that if your mailer has extensive processing, then it will likely fail (and it won't any log errors as Threads are not logged) if still processing beyond the time to complete the main controller action. This will only happen in development as the classes are un-instantiated upon completion. To fix this, just change this in your development.rb:

config.cache_classes = true

You can also use a background job process, but for lighter loads, Threads work great and are easy to implement.

Upvotes: 1

jtwg
jtwg

Reputation: 140

have you tried using delayed_job?

Upvotes: 0

Related Questions