module Canmoia::Notification

Attributes

notifications_declared[RW]

TODO add when needed extend ActiveSupport::Concern

Public Class Methods

extended(base) click to toggle source
# File lib/canmoia/features/notification.rb, line 9
def self.extended base
  base.notifications_declared = []
end

Public Instance Methods

notify(recipient_attribute = :responsible, on: -> { raise "on is required") click to toggle source
# File lib/canmoia/features/notification.rb, line 13
def notify recipient_attribute = :responsible, on: -> { raise "on is required" }, via: :email
  raise "Recipient named as '#{recipient_attribute}' not found for #{self.name}" unless instance_methods.include? recipient_attribute.to_sym

  on = [on] unless on.kind_of? Array

  on.each do |event|
    add_notification_method event, recipient_attribute, via
  end
end

Private Instance Methods

add_notification_method(event, recipient_attribute, via) click to toggle source

TODO use method missing

Calls superclass method
# File lib/canmoia/features/notification.rb, line 26
def add_notification_method event, recipient_attribute, via
  mail_method = "#{event}_notification_to_#{recipient_attribute}"

  notification = "#{event}_#{recipient_attribute}".to_sym
  unless notifications_declared.include? notification
    notifications_declared << notification
  else
    raise "Notification for event '#{event}' to recipient '#{recipient_attribute}' already declared!"
  end

  # TODO only define notification method if method is present on mailer
  # TODO create task to generate / update mailer with notification settings

  define_method "#{event}" do |*args|
    returned = super *args if defined? super
    # TODO better error message when mailer is not found
    # TODO allow specification of custom mailer
    mailer = "#{self.class.name}Mailer".classify.constantize

    # TODO better error message when mail method is not found
    entity = send recipient_attribute
    mail   = mailer.send mail_method, self, entity

    mail.deliver or returned
  end
end