Module: ActionMailer::CatchAll

Defined in:
lib/catch_all.rb,
lib/catch_all/version.rb

Constant Summary collapse

VERSION =
'0.0.4'

Class Method Summary collapse

Class Method Details

.disableObject



66
67
68
69
70
71
72
73
# File 'lib/catch_all.rb', line 66

def disable
  if enabled?
    ActionMailer::Base.class_eval do
      alias_method :mail, :mail_aliased_from_action_mailer_staging
      remove_method :mail_aliased_from_action_mailer_staging
    end
  end
end

.enable(*options) ⇒ Object



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
58
59
60
61
62
63
64
# File 'lib/catch_all.rb', line 11

def enable(*options)
  if options.length == 1 && options[0].is_a?(Hash)
    hash = options[0]

    whitelist_email_addresses = Array(hash[:whitelist]).flatten.compact
    fallback_email_addresses = Array(hash[:fallback]).flatten.compact
  else
    whitelist_email_addresses = options.flatten.compact
    fallback_email_addresses = whitelist_email_addresses
  end

  if fallback_email_addresses.length == 0
    Kernel.warn("No email addresses passed to ActionMailer::CatchAll!")
  end

  if enabled?
    disable
  end

  ActionMailer::Base.class_eval do
    alias_method :mail_aliased_from_action_mailer_staging, :mail

    define_method :mail do |*args, &block|
      mailer = mail_aliased_from_action_mailer_staging(*args, &block)

      to_values = Array(mailer[:to]).map do |field|
        field.value
      end

      to_values.flatten!

      # save the original to header
      mailer['X-Action-Mailer-Staging-Original-Email-To'] = to_values.inspect

      selected_to_addresses = to_values.select do |to|
        whitelist_email_addresses.any? do |email|
          if email.is_a?(Regexp)
            email =~ to
          else
            email == to
          end
        end
      end

      if selected_to_addresses.any?
        mailer[:to] = selected_to_addresses
      else
        mailer[:to] = fallback_email_addresses
      end

      mailer
    end
  end
end

.enabled?Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/catch_all.rb', line 7

def enabled?
  ActionMailer::Base.instance_methods.include?(:mail_aliased_from_action_mailer_staging)
end