Skip to content

Instantly share code, notes, and snippets.

@etagwerker
Created May 31, 2023 14:21
Show Gist options
  • Save etagwerker/e8fb0a1af37368c976d8c0b1e0ebbbec to your computer and use it in GitHub Desktop.
Save etagwerker/e8fb0a1af37368c976d8c0b1e0ebbbec to your computer and use it in GitHub Desktop.
# lib/rubocop/cop/rails/use_find_each.rb
module RuboCop
module Cop
module Rails
# This cop checks for usage of `all.each`.
#
# @example
# # bad
# Model.all.each do |record|
# # do something
# end
#
# # good
# Model.find_each do |record|
# # do something
# end
#
class UseFindEach < Cop
MSG = 'Use `find_each` instead of `all.each`.'.freeze
def_node_matcher :all_each?, '(send (send _ :all) :each)'
def on_send(node)
return unless all_each?(node)
add_offense(node, message: MSG, severity: :warning)
end
def autocorrect(node)
lambda do |corrector|
range = node.loc.selector.begin_pos...node.loc.expression.end_pos
corrector.replace(range, 'find_each')
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment