Skip to content

Instantly share code, notes, and snippets.

@bradleybuda
Last active December 16, 2015 12:49
Show Gist options
  • Save bradleybuda/5437563 to your computer and use it in GitHub Desktop.
Save bradleybuda/5437563 to your computer and use it in GitHub Desktop.
class AppShare < ActiveRecord::Base
belongs_to :app
belongs_to :sharer, class_name: 'User'
belongs_to :sharee, class_name: 'User'
has_many :notifications, foreign_key: :notified_object_id, conditions: {notified_object_type: 'AppShare'}, dependent: :destroy
after_commit :create_notification, on: :create
def create_notification
subject = "#{sharer.name} has given you access to #{app.name}"
body = "#{sharer.name} (#{sharer.email}) has granted you access to the #{app.name} account '#{app.username}'."
sharee.notify(subject, body, self)
end
end
Mailboxer.setup do |config|
config.uses_emails = false
config.search_enabled = false
end
ScheduleSendNotificationsJob:
every: 1m
class ScheduleSendNotificationsJob < Job
@queue = :high
def perform
# Find users with outstanding notifications, and deal with each in
# a different job
user_ids = User.
joins(:receipts).
where('confirmed_at IS NOT NULL').
where(receipts: {is_read: false}).
select('DISTINCT users.id').
map(&:id)
user_ids.each do |user_id|
SendNotificationsJob.create(id: user_id)
Rails.logger.info "Scheduled a job to send notifications to user #{user_id}"
end
end
end
class SendNotificationsJob < Job
@queue = :high
COOLDOWN_PERIOD = 4.minutes
def perform
user = User.find(options['id'])
if !user.confirmed?
Rails.logger.info "Not sending notifications to unconfirmed email #{user.email}"
return
end
ActiveRecord::Base.transaction do
receipts = user.receipts.where(is_read: false).lock(true)
most_recent = receipts.map(&:created_at).max
if most_recent && (most_recent < (Time.now - COOLDOWN_PERIOD))
notifications = Notification.find(receipts.map(&:notification_id))
Rails.logger.info "Sending #{notifications.size} notification(s) to #{user.email}"
NotificationsMailer.notifications_email(user, notifications).deliver
receipts.update_all(is_read: true)
else
Rails.logger.info "Waiting before sending notifications to #{user.email}"
end
end
end
end
class User < ActiveRecord::Base
acts_as_messageable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment