Skip to content

Commit 7dc5ed7

Browse files
authored
Merge pull request rubocop#892 from fatkodima/not_null_column-accept-virtual
Fix a false positive for `Rails/NotNullColumn` when adding a `:virtual` column
2 parents 0b97d60 + d60ff74 commit 7dc5ed7

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#887](https://github.com/rubocop/rubocop-rails/issues/887): Fix a false positive for `Rails/NotNullColumn` when adding a `:virtual` column. ([@fatkodima][])

lib/rubocop/cop/rails/not_null_column.rb

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class NotNullColumn < Base
2121
RESTRICT_ON_SEND = %i[add_column add_reference].freeze
2222

2323
def_node_matcher :add_not_null_column?, <<~PATTERN
24-
(send nil? :add_column _ _ _ (hash $...))
24+
(send nil? :add_column _ _ $_ (hash $...))
2525
PATTERN
2626

2727
def_node_matcher :add_not_null_reference?, <<~PATTERN
@@ -44,17 +44,20 @@ def on_send(node)
4444
private
4545

4646
def check_add_column(node)
47-
pairs = add_not_null_column?(node)
48-
check_pairs(pairs)
47+
add_not_null_column?(node) do |type, pairs|
48+
return if type.value == :virtual || type.value == 'virtual'
49+
50+
check_pairs(pairs)
51+
end
4952
end
5053

5154
def check_add_reference(node)
52-
pairs = add_not_null_reference?(node)
53-
check_pairs(pairs)
55+
add_not_null_reference?(node) do |pairs|
56+
check_pairs(pairs)
57+
end
5458
end
5559

5660
def check_pairs(pairs)
57-
return unless pairs
5861
return if pairs.any? { |pair| default_option?(pair) }
5962

6063
null_false = pairs.find { |pair| null_false?(pair) }

spec/rubocop/cop/rails/not_null_column_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@
2828
^^^^^^^^^^^ Do not add a NOT NULL column without a default value.
2929
RUBY
3030
end
31+
32+
it 'does not register an offense for virtual columns' do
33+
expect_no_offenses(<<~RUBY)
34+
add_column :users, :height_in, :virtual, as: "height_cm / 2.54", null: false, default: nil
35+
add_column :users, :height_in, 'virtual', as: "height_cm / 2.54", null: false, default: nil
36+
RUBY
37+
end
3138
end
3239

3340
context 'with null: true' do

0 commit comments

Comments
 (0)