Class: RuboCop::Cop::Rails::WhereEquals

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

Overview

Identifies places where manually constructed SQL in ‘where` and `where.not` can be replaced with `where(attribute: value)` and `where.not(attribute: value)`.

Examples:

# bad
User.where('name = ?', 'Gabe')
User.where.not('name = ?', 'Gabe')
User.where('name = :name', name: 'Gabe')
User.where('name IS NULL')
User.where('name IN (?)', ['john', 'jane'])
User.where('name IN (:names)', names: ['john', 'jane'])
User.where('users.name = :name', name: 'Gabe')

# good
User.where(name: 'Gabe')
User.where.not(name: 'Gabe')
User.where(name: nil)
User.where(name: ['john', 'jane'])
User.where(users: { name: 'Gabe' })

Constant Summary collapse

MSG =
'Use `%<good_method>s` instead of manually constructing SQL.'
RESTRICT_ON_SEND =
%i[where not].freeze
EQ_ANONYMOUS_RE =

column = ?

/\A([\w.]+)\s+=\s+\?\z/.freeze
IN_ANONYMOUS_RE =

column IN (?)

/\A([\w.]+)\s+IN\s+\(\?\)\z/i.freeze
EQ_NAMED_RE =

column = :column

/\A([\w.]+)\s+=\s+:(\w+)\z/.freeze
IN_NAMED_RE =

column IN (:column)

/\A([\w.]+)\s+IN\s+\(:(\w+)\)\z/i.freeze
IS_NULL_RE =

column IS NULL

/\A([\w.]+)\s+IS\s+NULL\z/i.freeze

Instance Method Summary collapse

Instance Method Details

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



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/rails/where_equals.rb', line 44

def on_send(node)
  return if node.method?(:not) && !where_not?(node)

  where_method_call?(node) do |template_node, value_node|
    value_node = value_node.first

    range = offense_range(node)

    column, value = extract_column_and_value(template_node, value_node)
    return unless value

    good_method = build_good_method(node.method_name, column, value)
    message = format(MSG, good_method: good_method)

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