Class: RuboCop::Cop::Appdev::PreferWhereOverFind
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Appdev::PreferWhereOverFind
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/appdev/prefer_where_over_find.rb
Overview
Forbids ‘Model.find(id)`, `Model.find_by(…)`, and `Model.find_by!(…)` in authored classroom code. The taught pattern is `Model.where({ :col => val }).first` / `.first!`, which makes the query object and indexed access explicit.
Autocorrectable. Behavior is preserved across the rewrite because ‘find` and `.first!` both raise `ActiveRecord::RecordNotFound`, and `find_by` and `.first` both return `nil` on miss.
Constant Summary collapse
- MSG_FIND =
"Use `.where({ :id => ... }).first!` instead of `.find(...)`."- MSG_FIND_BY =
"Use `.where(...).first` instead of `.find_by(...)`."- MSG_FIND_BY_BANG =
"Use `.where(...).first!` instead of `.find_by!(...)`."- RESTRICT_ON_SEND =
[:find, :find_by, :find_by!].freeze
Instance Method Summary collapse
Instance Method Details
#on_send(node) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/rubocop/cop/appdev/prefer_where_over_find.rb', line 32 def on_send(node) return unless node.receiver return if node.block_node return if node.arguments.empty? case node.method_name when :find handle_find(node) when :find_by handle_find_by(node, bang: false) when :find_by! handle_find_by(node, bang: true) end end |