Class: RuboCop::Cop::Neeto::MailerEmailKinds

Inherits:
Base
  • Object
show all
Includes:
VisibilityHelp
Defined in:
lib/rubocop/cop/neeto/mailer_email_kinds.rb

Overview

Every mailer declares which of its actions send transactional email (content we control) and which send user-generated email (content a person wrote). neeto-email-pipeline-engine sends user-generated email from a separate domain, so an undeclared action stays on the default domain. See neetozone/neeto-engineering#2319.

Actions are the public instance methods defined in the mailer's class body. Each one must be listed by name in exactly one list.

Examples:

# bad
class MessageMailer < ApplicationMailer
  def customer_email; end
end

# bad
class MessageMailer < ApplicationMailer
  email_kinds user_generated: %i[customer_email]

  def customer_email; end
  def member_email; end
end

# good
class MessageMailer < ApplicationMailer
  email_kinds transactional: %i[member_email], user_generated: %i[customer_email]

  def customer_email; end
  def member_email; end
end

Constant Summary collapse

MISSING_MSG =
"Declare `email_kinds` for %<actions>s, " \
"e.g. `email_kinds transactional: %%i[...], user_generated: %%i[...]`."
UNDECLARED_MSG =
"Add `%<action>s` to `transactional` or `user_generated` in `email_kinds`."
BOTH_MSG =
"`%<action>s` is in both `transactional` and `user_generated`. Keep it in one."
UNKNOWN_MSG =
"`%<action>s` is listed in `email_kinds` but this mailer doesn't define it."
NOT_A_LIST_MSG =
"List the actions by name, e.g. `%i[member_email]`."
LIST_KEYS =
%i[transactional user_generated].freeze

Instance Method Summary collapse

Instance Method Details

#email_kinds_call?(node) ⇒ Object



49
# File 'lib/rubocop/cop/neeto/mailer_email_kinds.rb', line 49

def_node_matcher :email_kinds_call?, "(send nil? :email_kinds ...)"

#on_class(node) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/neeto/mailer_email_kinds.rb', line 51

def on_class(node)
  name = node.identifier.short_name.to_s
  return if !name.end_with?("Mailer") || name == "ApplicationMailer"

  children = body_nodes(node)
  actions = children.select { |child| child.def_type? && node_visibility(child) == :public }
    .to_h { |def_node| [def_node.method_name, def_node] }
  return if actions.empty?

  declaration = children.find { |child| email_kinds_call?(child) }
  if declaration.nil?
    listed = actions.keys.map { |action| "`#{action}`" }.join(", ")
    add_offense(node.identifier, message: format(MISSING_MSG, actions: listed))
  else
    check_declaration(declaration, actions)
  end
end