Class: RuboCop::Cop::Rails::MailerName

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rails/mailer_name.rb

Overview

This cop enforces that mailer names end with ‘Mailer` suffix.

Without the ‘Mailer` suffix it isn’t immediately apparent what’s a mailer and which views are related to the mailer.

Examples:

# bad
class User < ActionMailer::Base
end

class User < ApplicationMailer
end

# good
class UserMailer < ActionMailer::Base
end

class UserMailer < ApplicationMailer
end

Constant Summary collapse

MSG =
'Mailer should end with `Mailer` suffix.'

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rubocop/cop/rails/mailer_name.rb', line 60

def autocorrect(node)
  lambda do |corrector|
    if node.casgn_type?
      name = node.children[1]
      corrector.replace(node.loc.name, "#{name}Mailer")
    else
      name = node.children.last
      corrector.replace(node.source_range, "#{name}Mailer")
    end
  end
end

#on_class(node) ⇒ Object



44
45
46
47
48
# File 'lib/rubocop/cop/rails/mailer_name.rb', line 44

def on_class(node)
  class_definition?(node) do |name_node|
    add_offense(name_node)
  end
end

#on_send(node) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/rails/mailer_name.rb', line 50

def on_send(node)
  return unless class_new_definition?(node)

  casgn_parent = node.each_ancestor(:casgn).first
  return unless casgn_parent

  name = casgn_parent.children[1]
  add_offense(casgn_parent, location: :name) unless mailer_suffix?(name)
end