Class: RuboCop::Cop::Rails::FindBy
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Rails::FindBy
- Extended by:
- AutoCorrector
- Includes:
- RangeHelp
- Defined in:
- lib/rubocop/cop/rails/find_by.rb
Overview
Identifies usages of ‘where.take` and change them to use `find_by` instead.
And ‘where(…).first` can return different results from `find_by`. (They order records differently, so the “first” record can be different.)
If you also want to detect ‘where.first`, you can set `IgnoreWhereFirst` to false.
Constant Summary collapse
- MSG =
'Use `find_by` instead of `where%<dot>s%<method>s`.'
- RESTRICT_ON_SEND =
%i[first take].freeze
Instance Method Summary collapse
- #on_send(node) ⇒ Object (also: #on_csend)
Instance Method Details
#on_send(node) ⇒ Object Also known as: on_csend
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/rubocop/cop/rails/find_by.rb', line 34 def on_send(node) return unless node.arguments.empty? && where_method?(node.receiver) return if ignore_where_first? && node.method?(:first) range = offense_range(node) add_offense(range, message: format(MSG, dot: node.loc.dot.source, method: node.method_name)) do |corrector| autocorrect(corrector, node) end end |