Class: Voltron::Notification

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/voltron/notification.rb

Defined Under Namespace

Classes: EmailNotification, SmsNotification

Constant Summary collapse

PERMITTED_ATTRIBUTES =
[:to, :from]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.format_output_of(json) ⇒ Object



59
60
61
62
63
# File 'app/models/voltron/notification.rb', line 59

def self.format_output_of(json)
  # Ensure returned object is an array of response hashes, for consistency
  out = Array.wrap((JSON.parse(json) rescue nil)).compact
  out.map { |h| h.with_indifferent_access }
end

Instance Method Details

#email(subject, **args, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/voltron/notification.rb', line 16

def email(subject, **args, &block)
  # Get the remaining args as params, that will eventually become assigns in the mailer template
  params = { subject: subject, notifyable.class.name.downcase => notifyable }.compact.merge(**args)

  # Build the options hash from the provided arguments
  options = { subject: subject }.merge(**args.select { |k, _| PERMITTED_ATTRIBUTES.include?(k.to_sym) })

  # Build a new SMS notification object
  notification_email = email_notifications.build(options)

  # Set the email vars (assigns)
  notification_email.vars = params

  # If a block is provided, allow calls to methods like `attach`
  notification_email.instance_exec(&block) if block_given?

  # Return the email notification instance
  notification_email
end

#sms(message, **args, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/models/voltron/notification.rb', line 36

def sms(message, **args, &block)
  # Build the options hash from the provided arguments
  options = { message: message, from: Voltron.config.notify.sms_from }.merge(**args)

  # Build a new SMS notification object
  notification_sms = sms_notifications.build(options)

  # If a block is provided, allow calls to methods like `attach`
  notification_sms.instance_exec(&block) if block_given?

  # Return the SMS notification instance
  notification_sms
end

#to(email, phone) ⇒ Object

Called from the before_validation callback within notifyable makes one final pass to set the email and phone as the to attribute If already set however, this does nothing. We do this because simply calling notifyable here returns nil until it’s actually saved



54
55
56
57
# File 'app/models/voltron/notification.rb', line 54

def to(email, phone)
  email_notifications.each { |n| n.to ||= email }
  sms_notifications.each { |n| n.to ||= phone }
end