Skip to content

Instantly share code, notes, and snippets.

@jmdfm
Forked from bradleybuda/app_share.rb
Created April 27, 2013 03:54
Show Gist options
  • Save jmdfm/5471828 to your computer and use it in GitHub Desktop.
Save jmdfm/5471828 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