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
13 changes: 12 additions & 1 deletion lib/rubocop/cop/type_toolkit/prefer_not_nil.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def replacement_for(argument)
#: (RuboCop::AST::SendNode, RuboCop::AST::Node, String) -> String
def correction_for(node, argument, replacement)
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
return replacement unless comments_inside_parentheses?(node)

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 All @@ -72,6 +72,17 @@ def correction_for(node, argument, replacement)
"#{grouped_source}.not_nil!"
end

#: (RuboCop::AST::SendNode) -> bool
def comments_inside_parentheses?(node)
contents_begin = node.loc.begin.end_pos
contents_end = node.loc.end.begin_pos

processed_source.comments.any? do |comment|
comment_range = comment.loc.expression
contents_begin <= comment_range.begin_pos && comment_range.end_pos <= contents_end
end
end

#: (RuboCop::AST::SendNode) -> bool
def nested_t_must?(node)
node.each_ancestor(:send).any? do |ancestor|
Expand Down
23 changes: 16 additions & 7 deletions spec/rubocop/cop/type_toolkit/prefer_not_nil_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def explicit_super
RUBY
end

it "autocorrects multiline calls with whitespace before the method" do
it "drops unnecessary grouping from multiline calls without comments" do
assert_offense(<<~RUBY)
first = T .must(
^^^^^^^^ #{MSG}
Expand All @@ -211,12 +211,21 @@ def explicit_super
RUBY

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

it "preserves a multiline call chain without parentheses" do
assert_offense(<<~RUBY)
variant = T.must(
^^^^^^^ #{MSG}
InventoryItemVariant.preload(:variant).where(inventory_item_id: @inventory_item_id).first!.variant
)
RUBY

assert_correction(<<~RUBY)
variant = InventoryItemVariant.preload(:variant).where(inventory_item_id: @inventory_item_id).first!.variant.not_nil!
RUBY
end

Expand Down
Loading