-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrename_column.rb
81 lines (74 loc) · 2.04 KB
/
rename_column.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true
module RuboCop
module Cop
module Migration
# Avoid renaming columns that are in use.
#
# It will cause errors in your application.
# A safer approach is to:
#
# 1. Create a new column
# 2. Write to both columns
# 3. Backfill data from the old column to the new column
# 4. Move reads from the old column to the new column
# 5. Stop writing to the old column
# 6. Drop the old column
#
# @safety
# Only meaningful if the column is in use.
#
# @example
# # bad
# class RenameUsersSettingsToProperties < ActiveRecord::Migration[7.0]
# def change
# rename_column :users, :settings, :properties
# end
# end
#
# # good
# class AddUsersProperties < ActiveRecord::Migration[7.0]
# def change
# add_column :users, :properties, :jsonb
# end
# end
#
# class User < ApplicationRecord
# self.ignored_columns += %w[settings]
# end
#
# class RemoveUsersSettings < ActiveRecord::Migration[7.0]
# def change
# remove_column :users, :settings
# end
# end
class RenameColumn < RuboCop::Cop::Base
MSG = 'Avoid renaming columns that are in use.'
RESTRICT_ON_SEND = %i[
rename_column
].freeze
# @param node [RuboCop::AST::SendNode]
# @return [void]
def on_send(node)
return unless bad?(node)
add_offense(node)
end
private
# @!method rename_column?(node)
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def_node_matcher :rename_column?, <<~PATTERN
(send
nil?
:rename_column
...
)
PATTERN
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def bad?(node)
rename_column?(node)
end
end
end
end
end