Class: RuboCop::Cop::Rails::WhereExists

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rails/where_exists.rb

Overview

Enforces consistent style when using ‘exists?`.

Two styles are supported for this cop. When EnforcedStyle is ‘exists’ then the cop enforces ‘exists?(…)` over `where(…).exists?`.

When EnforcedStyle is ‘where’ then the cop enforces ‘where(…).exists?` over `exists?(…)`.

Examples:

EnforcedStyle: exists (default)

# bad
User.where(name: 'john').exists?
User.where(['name = ?', 'john']).exists?
User.where('name = ?', 'john').exists?
user.posts.where(published: true).exists?

# good
User.exists?(name: 'john')
User.where('length(name) > 10').exists?
user.posts.exists?(published: true)

EnforcedStyle: where

# bad
User.exists?(name: 'john')
User.exists?(['name = ?', 'john'])
user.posts.exists?(published: true)

# good
User.where(name: 'john').exists?
User.where(['name = ?', 'john']).exists?
User.where('name = ?', 'john').exists?
user.posts.where(published: true).exists?
User.where('length(name) > 10').exists?

Constant Summary collapse

MSG =
'Prefer `%<good_method>s` over `%<bad_method>s`.'
RESTRICT_ON_SEND =
%i[exists?].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rubocop/cop/rails/where_exists.rb', line 65

def on_send(node)
  find_offenses(node) do |args|
    return unless convertable_args?(args)

    range = correction_range(node)
    good_method = build_good_method(args, dot: node.loc.dot)
    message = format(MSG, good_method: good_method, bad_method: range.source)

    add_offense(range, message: message) do |corrector|
      corrector.replace(range, good_method)
    end
  end
end