class Loco::Broadcaster

Public Class Methods

call(obj, event, recipients: nil, payload: nil) click to toggle source
# File lib/loco/broadcaster.rb, line 6
def call(obj, event, recipients: nil, payload: nil)
  payload ||= {}
  payload[:loco] = { idempotency_key: SecureRandom.hex }
  send_notifications(obj, event, process_recipients(recipients), payload)
end

Private Class Methods

keify_recipient(recipient) click to toggle source
# File lib/loco/broadcaster.rb, line 35
def keify_recipient(recipient)
  case recipient
  when String then { 'token' => recipient }
  when Class then { 'class' => recipient.name }
  else recipient
  end
end
process_recipients(recipients) click to toggle source
# File lib/loco/broadcaster.rb, line 14
def process_recipients(recipients)
  recipients = [:all] if recipients.nil?
  recipients = [recipients] unless recipients.is_a?(Array)
  recipients = recipients.map { |e| e.nil? ? :all : e }
  recipients = [:all] if recipients.include?(:all)
  recipients
end
send_notification(recipient, notification, sync_time) click to toggle source
# File lib/loco/broadcaster.rb, line 43
def send_notification(recipient, notification, sync_time)
  if notification.recipient_id
    Sender.(recipient, loco: { notification: notification.compact })
    Sender.(recipient, loco: { sync_time: sync_time })
  else
    SenderJob.perform_later(recipient, loco: { notification: notification.compact })
    SenderJob.perform_later(recipient, loco: { sync_time: sync_time })
  end
end
send_notifications(obj, event, recipients, payload) click to toggle source
# File lib/loco/broadcaster.rb, line 22
def send_notifications(obj, event, recipients, payload)
  recipients.each do |recipient|
    notification = Notification.create!(
      obj: obj,
      event: event,
      recipient: recipient,
      data: payload
    )
    sync_time = notification.created_at.iso8601(6)
    send_notification(keify_recipient(recipient), notification, sync_time)
  end
end