Remove code duplication for catching errors when sending mails

This commit is contained in:
Patrick Gansterer 2017-08-18 01:04:41 +02:00
parent 0ed3b7b7c3
commit 2264351cf5
4 changed files with 27 additions and 22 deletions

View file

@ -92,4 +92,17 @@ class Mailer < ActionMailer::Base
super
end
def self.deliver_now_with_user_locale(user, &block)
I18n.with_locale(user.settings['profile']['language']) do
self.deliver_now &block
end
end
def self.deliver_now
message = yield
message.deliver_now
rescue => error
Rails.logger.warn "Can't deliver mail to #{message.to[0]}: #{error.message}"
end
end

View file

@ -13,12 +13,10 @@ class UserNotifier
Order.find(order_id).group_orders.each do |group_order|
next if group_order.ordergroup.nil?
group_order.ordergroup.users.each do |user|
begin
I18n.with_locale(user.settings['profile']['language']) do
Mailer.order_result(user, group_order).deliver if user.settings.notify["order_finished"]
if user.settings.notify['order_finished']
Mailer.deliver_now_with_user_locale user do
Mailer.order_result(user, group_order)
end
rescue
Rails.logger.warn "Can't deliver mail to #{user.email}"
end
end
end
@ -31,12 +29,10 @@ class UserNotifier
transaction = FinancialTransaction.find transaction_id
Ordergroup.find(ordergroup_id).users.each do |user|
begin
I18n.with_locale(user.settings['profile']['language']) do
Mailer.negative_balance(user, transaction).deliver if user.settings.notify["negative_balance"]
if user.settings.notify['negative_balance']
Mailer.deliver_now_with_user_locale user do
Mailer.negative_balance(user, transaction)
end
rescue
Rails.logger.warn "Can't deliver mail to #{user.email}"
end
end
end

View file

@ -7,10 +7,10 @@ namespace :foodsoft do
for task in tasks
rake_say "Send notifications for #{task.name} to .."
for user in task.users
begin
Mailer.upcoming_tasks(user, task).deliver_now if user.settings.notify['upcoming_tasks'] == 1
rescue
rake_say "deliver aborted for #{user.email}.."
if user.settings.notify['upcoming_tasks']
Mailer.deliver_now_with_user_locale user do
Mailer.upcoming_tasks(user, task)
end
end
end
end
@ -26,10 +26,8 @@ namespace :foodsoft do
rake_say "Notify workgroup: #{workgroup.name} for task #{task.name}"
for user in workgroup.users
if user.receive_email?
begin
Mailer.not_enough_users_assigned(task, user).deliver_now
rescue
rake_say "deliver aborted for #{user.email}"
Mailer.deliver_now_with_user_locale user do
Mailer.not_enough_users_assigned(task, user)
end
end
end

View file

@ -7,10 +7,8 @@ class MessageNotifier < UserNotifier
message.recipients.each do |recipient|
if recipient.receive_email?
begin
MessagesMailer.foodsoft_message(recipient, message).deliver
rescue
Rails.logger.warn "Deliver failed for user \##{recipient.id}: #{recipient.email}"
Mailer.deliver_now_with_user_locale recipient do
MessagesMailer.foodsoft_message(recipient, message)
end
end
end