aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_mailbox/router/route.rb
blob: 24be8d4804440876b78f0b7b4c47ec4235479496 (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
class ActionMailbox::Router::Route
  attr_reader :address, :mailbox_name

  def initialize(address, to:)
    @address, @mailbox_name = address, to

    ensure_valid_address
  end

  def match?(inbound_email)
    case address
    when String
      inbound_email.mail.recipients.any? { |recipient| address.casecmp?(recipient) }
    when Regexp
      inbound_email.mail.recipients.any? { |recipient| address.match?(recipient) }
    when Proc
      address.call(inbound_email)
    else
      address.match?(inbound_email)
    end
  end

  def mailbox_class
    "#{mailbox_name.to_s.camelize}Mailbox".constantize
  end

  private
    def ensure_valid_address
      unless [ String, Regexp, Proc ].any? { |klass| address.is_a?(klass) } || address.respond_to?(:match?)
        raise ArgumentError, "Expected a String, Regexp, Proc, or matchable, got #{address.inspect}"
      end
    end
end