Skip to content

Commit edeaa45

Browse files
authored
Merge pull request #1165 from fatkodima/fix-save_bang-parenthesis
Fix `Rails/SaveBang` to ignore parenthesis
2 parents 543c2a7 + 0692aa3 commit edeaa45

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1160](https://github.com/rubocop/rubocop-rails/issues/1160): Fix `Rails/SaveBang` to ignore parenthesis. ([@fatkodima][])

lib/rubocop/cop/rails/save_bang.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,10 @@ def check_used_in_condition_or_compound_boolean(node)
235235

236236
def in_condition_or_compound_boolean?(node)
237237
node = node.block_node || node
238-
parent = node.parent
238+
parent = node.each_ancestor.find { |ancestor| !ancestor.begin_type? }
239239
return false unless parent
240240

241-
operator_or_single_negative?(parent) || (conditional?(parent) && node == parent.condition)
241+
operator_or_single_negative?(parent) || (conditional?(parent) && node == deparenthesize(parent.condition))
242242
end
243243

244244
def operator_or_single_negative?(node)
@@ -249,6 +249,11 @@ def conditional?(parent)
249249
parent.if_type? || parent.case_type?
250250
end
251251

252+
def deparenthesize(node)
253+
node = node.children.last while node.begin_type?
254+
node
255+
end
256+
252257
def checked_immediately?(node)
253258
node.parent && call_to_persisted?(node.parent)
254259
end

spec/rubocop/cop/rails/save_bang_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,19 @@
170170
end
171171
end
172172

173+
it "when using #{method} wrapped within parenthesis with if" do
174+
if update
175+
expect_no_offenses(<<~RUBY, method: method)
176+
if (object.#{method}); something; end
177+
RUBY
178+
else
179+
expect_offense(<<~RUBY, method: method)
180+
if (object.#{method}); something; end
181+
^{method} `#{method}` returns a model which is always truthy.
182+
RUBY
183+
end
184+
end
185+
173186
it "when using #{method} with if with block" do
174187
if update
175188
expect_no_offenses(<<~RUBY)

0 commit comments

Comments
 (0)