Skip to content

Commit

Permalink
Add Rubocop rule to catch .any? without block
Browse files Browse the repository at this point in the history
  • Loading branch information
rmosolgo committed Nov 21, 2024
1 parent 1351395 commit a863faf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
20 changes: 15 additions & 5 deletions cop/development/none_without_block_cop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ module Development
# @see https://github.com/rmosolgo/graphql-ruby/pull/2090
class NoneWithoutBlockCop < RuboCop::Cop::Cop
MSG = <<-MD
Instead of `.none?` without a block:
Instead of `.none?` or `.any?` without a block:
- Use `.empty?` to check for an empty collection (faster)
- Add a block to explicitly check for `false` (more clear)
Run `-a` to replace this with `.empty?`.
Run `-a` to replace this with `%{bang}.empty?`.
MD
def on_block(node)
# Since this method was called with a block, it can't be
Expand All @@ -22,14 +22,24 @@ def on_block(node)
end

def on_send(node)
if !ignored_node?(node) && node.method_name == :none? && node.arguments.size == 0
add_offense(node)
if !ignored_node?(node) && (node.method_name == :none? || node.method_name == :any?) && node.arguments.size == 0
add_offense(node, message: MSG % { bang: node.method_name == :none? ? "" : "!.." } )
end
end

def autocorrect(node)
lambda do |corrector|
corrector.replace(node.location.selector, "empty?")
if node.method_name == :none?
corrector.replace(node.location.selector, "empty?")
else
# Backtrack to any chained method calls so we can insert `!` before them
full_exp = node
while node.parent.send_type?
full_exp = node.parent
end
new_source = "!" + full_exp.source_range.source.sub("any?", "empty?")
corrector.replace(full_exp, new_source)
end
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/graphql/dataloader/source.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def load_all(values)
end
}

if pending_keys.size.positive?
if !pending_keys.empty?
sync(pending_keys)
end

Expand Down

0 comments on commit a863faf

Please sign in to comment.