Skip to content

Instantly share code, notes, and snippets.

@delba
Created April 22, 2014 14:51
Show Gist options
  • Save delba/11182239 to your computer and use it in GitHub Desktop.
Save delba/11182239 to your computer and use it in GitHub Desktop.
Weekly notification draft
class Expert < ActiveRecord::Base
include Notifiable
has_many :trackings do
def recent
where('created_at >= ?', proxy_association.owner.notified_at)
end
end
end
require 'active_support/concern'
module Notifiable
extend ActiveSupport::Concern
included do
scope :notified, -> { where.not(notified_at: nil) }
scope :notified_one_week_ago, -> { notified.where('notified_at <= ?', 1.week.ago) }
scope :with_recent_trackings, -> { joins(:trackings).where('trackings.created_at >= users.notified_at') }
end
class_methods do
def deliver_weekly_notifications
notified_one_week_ago.with_recent_trackings.each do |expert|
expert.deliver_weekly_notification
end
end
end
def notified?
!!notified_at
end
def deliver_first_notification
NotificationMailer.first_notification(self).deliver
end
def deliver_weekly_notification
NotificationMailer.weekly_notification(self).deliver
end
end
class NotificationMailer < ActionMailer::Base
after_action :set_notified_at
def weekly_notification(expert)
@expert = user
@trackings = @expert.trackings.recent
mail to: @expert.email, subject: 'Weekly Notification'
end
def first_notification(expert)
@expert = expert
@tracking = @expert.trackings.first
mail to: @expert.email, subject: 'First notification'
end
private
def set_notified_at
@expert.update_column(:notified_at, Time.current)
end
end
every 15.minutes do
Expert.deliver_weekly_notifications
end
class Tracking < ActiveRecord::Base
belongs_to :expert
after_create :deliver_first_notification, unless: -> tracking { tracking.expert.notified? }
private
def deliver_first_notification
expert.deliver_first_notification
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment