Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/rubocop/cop/type_toolkit/prefer_not_nil.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,16 @@ def extract_t_must_argument(node)
#: (RuboCop::AST::Node) -> String
def replacement_for(argument)
source = argument.source

source = "(#{source})" if requires_parentheses?(argument)

"#{source}.not_nil!"
end

#: (RuboCop::AST::SendNode, RuboCop::AST::Node, String) -> String
def correction_for(node, argument, replacement)
return replacement unless node.multiline?
return replacement unless node.multiline? && node.parenthesized_call?
return replacement if argument.first_line == node.loc.begin.line && argument.last_line == node.loc.end.line

grouped_range = node.source_range.with(begin_pos: node.loc.begin.begin_pos, end_pos: node.loc.end.end_pos)
grouped_source = grouped_range.source
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/type_toolkit/prefer_not_nil_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,19 @@ def explicit_super
RUBY
end

it "autocorrects multiline command calls" do
assert_offense(<<~RUBY)
T.must foo
^^^^^^^^^^ #{MSG}
.bar
RUBY

assert_correction(<<~RUBY)
foo
.bar.not_nil!
RUBY
end

it "does not add unnecessary parentheses to parenthesized calls" do
assert_offense(<<~RUBY)
value = T.must(fetch(value))
Expand Down Expand Up @@ -151,6 +164,19 @@ def explicit_super
RUBY
end

it "does not group an argument that makes the call multiline" do
assert_offense(<<~RUBY)
T.must(foo
^^^^^^^^^^ #{MSG}
.bar)
RUBY

assert_correction(<<~RUBY)
foo
.bar.not_nil!
RUBY
end

it "preserves comments in multiline calls" do
assert_offense(<<~RUBY)
value = T.must(
Expand Down
Loading