BigW Consortium Gitlab

reversible_add_column_with_default.rb 1.02 KB
Newer Older
1 2 3 4 5 6 7
require_relative '../../migration_helpers'

module RuboCop
  module Cop
    module Migration
      # Cop that checks if `add_column_with_default` is used with `up`/`down` methods
      # and not `change`.
8
      class ReversibleAddColumnWithDefault < RuboCop::Cop::Cop
9 10
        include MigrationHelpers

11 12 13 14 15 16 17 18
        def_node_matcher :add_column_with_default?, <<~PATTERN
          (send nil :add_column_with_default $...)
        PATTERN

        def_node_matcher :defines_change?, <<~PATTERN
          (def :change ...)
        PATTERN

19
        MSG = '`add_column_with_default` is not reversible so you must manually define ' \
20
          'the `up` and `down` methods in your migration class, using `remove_column` in `down`'.freeze
21 22 23

        def on_send(node)
          return unless in_migration?(node)
24
          return unless add_column_with_default?(node)
25 26

          node.each_ancestor(:def) do |def_node|
27
            next unless defines_change?(def_node)
28 29 30 31 32 33 34 35

            add_offense(def_node, :name)
          end
        end
      end
    end
  end
end