Class: RuboCop::Cop::Sevencop::RailsWhereNot

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sevencop/rails_where_not.rb

Overview

Identifies passing multi-elements Hash literal to ‘where.not`.

Examples:


# bad
where.not(key1: value1, key2: value2)

# good
where.not(key1: value1).where.not(key2: value2)

Constant Summary collapse

MSG =
'Use `where.not(key1: value1).where.not(key2: value2)` style.'

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rubocop/cop/sevencop/rails_where_not.rb', line 30

def on_send(node)
  return unless rails_where_not_with_multiple_elements_hash?(node)

  add_offense(node) do |corrector|
    pairs = node.children[2].children
    last_end_pos = pairs[0].source_range.end_pos
    pairs[1..].each do |pair|
      corrector.remove(pair.source_range.with(begin_pos: last_end_pos))
      last_end_pos = pair.source_range.end_pos
      corrector.insert_after(node, ".where.not(#{pair.source})")
    end
  end
end

#rails_where_not_with_multiple_elements_hash?(node) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/rubocop/cop/sevencop/rails_where_not.rb', line 22

def_node_matcher :rails_where_not_with_multiple_elements_hash?, <<~PATTERN
  (send
    (send _ :where) :not
    (hash
      (pair _ _)
      (pair _ _)+))
PATTERN