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

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

Overview

This cop 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 `%<corrected_class_name>s` that matches the file name.'

Instance Method Summary collapse

Instance Method Details

#on_class(node) ⇒ Object



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

def on_class(node)
  snake_class_name = to_snakecase(node.identifier.source)

  return if snake_class_name == basename_without_timestamp

  corrected_class_name = to_camelcase(basename_without_timestamp)
  message = format(MSG, corrected_class_name: corrected_class_name)

  add_offense(node.identifier, message: message) do |corrector|
    corrector.replace(node.identifier, corrected_class_name)
  end
end