Skip to content

Commit 1e09c35

Browse files
committed
[Fix rubocop#776] Fix an incorrect autocorrect for Rails/Presence
Fixes rubocop#776. This PR fixes an incorrect autocorrect for `Rails/Presence` when using arithmetic operation in `else` branch.
1 parent 6b5424e commit 1e09c35

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#776](https://github.com/rubocop/rubocop-rails/issues/776): Fix an incorrect autocorrect for `Rails/Presence` when using arithmetic operation in `else` branch. ([@koic][])

lib/rubocop/cop/rails/presence.rb

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,19 +122,19 @@ def replacement(receiver, other)
122122
end
123123

124124
def build_source_for_or_method(other)
125-
if other.parenthesized? || other.method?('[]') || !other.arguments?
125+
if other.parenthesized? || other.method?('[]') || other.arithmetic_operation? || !other.arguments?
126126
" || #{other.source}"
127127
else
128-
method = range_between(
129-
other.source_range.begin_pos,
130-
other.first_argument.source_range.begin_pos - 1
131-
).source
132-
128+
method = method_range(other).source
133129
arguments = other.arguments.map(&:source).join(', ')
134130

135131
" || #{method}(#{arguments})"
136132
end
137133
end
134+
135+
def method_range(node)
136+
range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos - 1)
137+
end
138138
end
139139
end
140140
end

spec/rubocop/cop/rails/presence_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,22 @@
4949
end
5050
RUBY
5151

52+
it_behaves_like 'offense', <<~RUBY.chomp, 'a.presence || b.to_f + 12.0', 1, 5
53+
if a.present?
54+
a
55+
else
56+
b.to_f + 12.0
57+
end
58+
RUBY
59+
60+
it_behaves_like 'offense', <<~RUBY.chomp, 'a.presence || b.to_f * 12.0', 1, 5
61+
if a.present?
62+
a
63+
else
64+
b.to_f * 12.0
65+
end
66+
RUBY
67+
5268
it_behaves_like 'offense', 'a if a.present?', 'a.presence', 1, 1
5369
it_behaves_like 'offense', 'a unless a.blank?', 'a.presence', 1, 1
5470
it_behaves_like 'offense', <<~RUBY.chomp, <<~FIXED.chomp, 1, 7

0 commit comments

Comments
 (0)