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



57
58
59
60
61
# File 'app/models/voltron/notification.rb', line 57

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, options = {}, &block) ⇒ Object



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

def email(subject, options={}, &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(options)

  # Build the options hash from the provided arguments
  options = { subject: subject }.merge(options.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, options = {}, &block) ⇒ Object



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

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

  # 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



52
53
54
55
# File 'app/models/voltron/notification.rb', line 52

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