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

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rails/where_exists.rb

Overview

This cop enforces the use of ‘exists?(…)` over `where(…).exists?`.

Examples:

# 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)

Constant Summary collapse

MSG =
'Prefer `%<good_method>s` over `%<bad_method>s`.'

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/rubocop/cop/rails/where_exists.rb', line 37

def autocorrect(node)
  args = where_exists_call?(node)

  lambda do |corrector|
    corrector.replace(
      correction_range(node),
      build_good_method(args)
    )
  end
end

#on_send(node) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/rubocop/cop/rails/where_exists.rb', line 27

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

    range = correction_range(node)
    message = format(MSG, good_method: build_good_method(args), bad_method: range.source)
    add_offense(node, location: range, message: message)
  end
end