Class: RuboCop::Cop::Rails::MigrationClassName

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
MigrationsHelper
Defined in:
lib/rubocop/cop/rails/migration_class_name.rb

Overview

Makes sure that each migration file defines a migration class whose name matches the file name. (e.g. ‘20220224111111_create_users.rb` should define `CreateUsers` class.)

Examples:

# db/migrate/20220224111111_create_users.rb

# bad
class SellBooks < ActiveRecord::Migration[7.0]
end

# good
class CreateUsers < ActiveRecord::Migration[7.0]
end

Constant Summary collapse

MSG =
'Replace with `%<camelized_basename>s` that matches the file name.'

Instance Method Summary collapse

Methods included from MigrationsHelper

#in_migration?

Instance Method Details

#on_class(node) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/rails/migration_class_name.rb', line 27

def on_class(node)
  return unless migration_class?(node)

  basename = basename_without_timestamp_and_suffix(processed_source.file_path)

  class_identifier = node.identifier.location.name
  camelized_basename = camelize(basename)
  return if class_identifier.source.casecmp(camelized_basename).zero?

  message = format(MSG, camelized_basename: camelized_basename)

  add_offense(class_identifier, message: message) do |corrector|
    corrector.replace(class_identifier, camelized_basename)
  end
end