|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module RuboCop |
| 4 | + module Cop |
| 5 | + module Rails |
| 6 | + # This cop makes sure that each migration file defines a migration class |
| 7 | + # whose name matches the file name. |
| 8 | + # (e.g. `20220224111111_create_users.rb` should define `CreateUsers` class.) |
| 9 | + # |
| 10 | + # @example |
| 11 | + # # db/migrate/20220224111111_create_users.rb |
| 12 | + # |
| 13 | + # # bad |
| 14 | + # class SellBooks < ActiveRecord::Migration[7.0] |
| 15 | + # end |
| 16 | + # |
| 17 | + # # good |
| 18 | + # class CreateUsers < ActiveRecord::Migration[7.0] |
| 19 | + # end |
| 20 | + # |
| 21 | + class MigrationClassName < Base |
| 22 | + extend AutoCorrector |
| 23 | + |
| 24 | + MSG = 'Replace with `%<corrected_class_name>s` that matches the file name.' |
| 25 | + |
| 26 | + def on_class(node) |
| 27 | + snake_class_name = to_snakecase(node.identifier.source) |
| 28 | + |
| 29 | + return if snake_class_name == basename_without_timestamp |
| 30 | + |
| 31 | + corrected_class_name = to_camelcase(basename_without_timestamp) |
| 32 | + message = format(MSG, corrected_class_name: corrected_class_name) |
| 33 | + |
| 34 | + add_offense(node.identifier, message: message) do |corrector| |
| 35 | + corrector.replace(node.identifier, corrected_class_name) |
| 36 | + end |
| 37 | + end |
| 38 | + |
| 39 | + private |
| 40 | + |
| 41 | + def basename_without_timestamp |
| 42 | + filepath = processed_source.file_path |
| 43 | + basename = File.basename(filepath, '.rb') |
| 44 | + basename.sub(/\A\d+_/, '') |
| 45 | + end |
| 46 | + |
| 47 | + def to_camelcase(word) |
| 48 | + word.split('_').map(&:capitalize).join |
| 49 | + end |
| 50 | + |
| 51 | + def to_snakecase(word) |
| 52 | + word |
| 53 | + .gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2') |
| 54 | + .gsub(/([a-z\d])([A-Z])/, '\1_\2') |
| 55 | + .tr('-', '_') |
| 56 | + .downcase |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + end |
| 61 | +end |
0 commit comments