Class: RuboCop::Cop::Rails::Presence

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

Overview

Checks code that can be written more easily using ‘Object#presence` defined by Active Support.

Examples:

# bad
a.present? ? a : nil

# bad
!a.present? ? nil : a

# bad
a.blank? ? nil : a

# bad
!a.blank? ? a : nil

# good
a.presence
# bad
a.present? ? a : b

# bad
!a.present? ? b : a

# bad
a.blank? ? b : a

# bad
!a.blank? ? a : b

# good
a.presence || b

Constant Summary collapse

MSG =
'Use `%<prefer>s` instead of `%<current>s`.'

Instance Method Summary collapse

Instance Method Details

#on_if(node) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/rubocop/cop/rails/presence.rb', line 76

def on_if(node)
  return if ignore_if_node?(node)

  redundant_receiver_and_other(node) do |receiver, other|
    return if ignore_other_node?(other) || receiver.nil?

    register_offense(node, receiver, other)
  end

  redundant_negative_receiver_and_other(node) do |receiver, other|
    return if ignore_other_node?(other) || receiver.nil?

    register_offense(node, receiver, other)
  end
end