Class: RuboCop::Cop::Sevencop::RailsOrderFieldArelSql

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

Overview

Identifies a String including “field” is passed to ‘order` or `reorder`.

Examples:


# bad
articles.order('field(id, ?)', a)

# good
articles.order(Arel.sql('field(id, ?)'), a)

# bad
reorder('field(id, ?)', a)

# good
reorder(Arel.sql('field(id, ?)'), a)

Cop Safety Information:

  • This cop is unsafe because it can register a false positive.

Constant Summary collapse

MSG =
'Wrap safe SQL String by `Arel.sql`.'
RESTRICT_ON_SEND =
%i[
  order
  reorder
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object

Parameters:

  • node (RuboCop::AST::SendNode)


48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/sevencop/rails_order_field_arel_sql.rb', line 48

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

  first_argument_node = node.first_argument
  add_offense(first_argument_node) do |corrector|
    corrector.replace(
      node.first_argument,
      "Arel.sql(#{first_argument_node.source})"
    )
  end
end

#order_with_field?(node) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/sevencop/rails_order_field_arel_sql.rb', line 36

def_node_matcher :order_with_field?, <<~PATTERN
  (send
    _ _
    {
      (str /field(.+)/i) |
      (dstr <(str /field(.+)/i) ...>)
    }
    ...
  )
PATTERN