refactors email digest

This commit is contained in:
rgarcia
2016-08-03 19:33:37 +02:00
parent 6281af2a7d
commit b087fe8fb7
4 changed files with 26 additions and 13 deletions

View File

@@ -60,8 +60,8 @@ class Mailer < ApplicationMailer
end
end
def proposal_notification_digest(user)
@notifications = user.notifications.where(notifiable_type: "ProposalNotification")
def proposal_notification_digest(user, notifications)
@notifications = notifications
with_user(user) do
mail(to: user.email, subject: t('mailers.proposal_notification_digest.title', org_name: Setting['org_name']))

View File

@@ -4,8 +4,10 @@ class Notification < ActiveRecord::Base
scope :unread, -> { all }
scope :recent, -> { order(id: :desc) }
scope :not_emailed, -> { where(emailed_at: nil) }
scope :for_render, -> { includes(:notifiable) }
def timestamp
notifiable.created_at
end

View File

@@ -1,13 +1,22 @@
class EmailDigest
def initialize
attr_accessor :user, :notifications
def initialize(user)
@user = user
end
def create
User.email_digest.each do |user|
if user.notifications.where(notifiable_type: "ProposalNotification").any?
Mailer.proposal_notification_digest(user).deliver_later
def notifications
user.notifications.not_emailed.where(notifiable_type: "ProposalNotification").to_a
end
def pending_notifications?
notifications.any?
end
def deliver
if pending_notifications?
Mailer.proposal_notification_digest(user, notifications).deliver_later
end
end

View File

@@ -2,8 +2,10 @@ namespace :emails do
desc "Sends email digest of proposal notifications to each user"
task digest: :environment do
email_digest = EmailDigest.new
email_digest.create
User.email_digest.find_each do |user|
email_digest = EmailDigest.new(user)
email_digest.deliver
end
end
end