Skip to content

Commit

Permalink
Make InternalAffairs/NodeTypePredicate aware of safe navigation ope…
Browse files Browse the repository at this point in the history
…rator
  • Loading branch information
koic committed Dec 25, 2024
1 parent b769939 commit 30cbafa
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion lib/rubocop/cop/bundler/gem_comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def contains_checked_options?(node)
end

def gem_options(node)
return [] unless node.last_argument&.type == :hash
return [] unless node.last_argument&.hash_type?

node.last_argument.keys.map(&:value)
end
Expand Down
7 changes: 4 additions & 3 deletions lib/rubocop/cop/internal_affairs/node_type_predicate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,17 @@ class NodeTypePredicate < Base

# @!method node_type_check(node)
def_node_matcher :node_type_check, <<~PATTERN
(send (send $_ :type) :== (sym $_))
(send (call _ :type) :== (sym $_))
PATTERN

def on_send(node)
node_type_check(node) do |receiver, node_type|
node_type_check(node) do |node_type|
return unless Parser::Meta::NODE_TYPES.include?(node_type)

message = format(MSG, type: node_type)
add_offense(node, message: message) do |corrector|
range = node.source_range.with(begin_pos: receiver.source_range.end_pos + 1)
range = node.receiver.loc.selector.join(node.source_range.end)

corrector.replace(range, "#{node_type}_type?")
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def check_indented(children)

def base_column(child)
grandparent = child.parent.parent
if grandparent&.type == :pair
if grandparent&.pair_type?
grandparent.loc.column
else
child.source_range.source_line =~ /\S/
Expand Down
15 changes: 14 additions & 1 deletion spec/rubocop/cop/internal_affairs/node_type_predicate_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,21 @@
end
end

context 'comparison node type check with safe navigation operator' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
node&.type == :send
^^^^^^^^^^^^^^^^^^^ Use `#send_type?` to check node type.
RUBY

expect_correction(<<~RUBY)
node&.send_type?
RUBY
end
end

it 'does not register an offense for a predicate node type check' do
expect_no_offenses(<<~RUBY, 'example_spec.rb')
expect_no_offenses(<<~RUBY)
node.send_type?
RUBY
end
Expand Down

0 comments on commit 30cbafa

Please sign in to comment.