aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_mailbox/base.rb
blob: 55914401e167a03b892687281a79930081c75b37 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require "active_support/rescuable"

require "action_mailbox/callbacks"
require "action_mailbox/routing"

class ActionMailbox::Base
  include ActiveSupport::Rescuable
  include ActionMailbox::Callbacks, ActionMailbox::Routing

  attr_reader :inbound_email
  delegate :mail, :delivered!, :bounced!, to: :inbound_email

  delegate :logger, to: ActionMailbox

  def self.receive(inbound_email)
    new(inbound_email).perform_processing
  end

  def initialize(inbound_email)
    @inbound_email = inbound_email
  end

  def perform_processing
    track_status_of_inbound_email do
      run_callbacks :process do
        process
      end
    end
  rescue => exception
    # TODO: Include a reference to the inbound_email in the exception raised so error handling becomes easier
    rescue_with_handler(exception) || raise
  end

  def process
    # Overwrite in subclasses
  end

  def finished_processing?
    inbound_email.delivered? || inbound_email.bounced?
  end


  def bounce_with(message)
    inbound_email.bounced!
    message.deliver_later
  end

  private
    def track_status_of_inbound_email
      inbound_email.processing!
      yield
      inbound_email.delivered! unless inbound_email.bounced?
    rescue
      inbound_email.failed!
      raise
    end
end