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
# bad
a.present? ? a.foo : nil

# bad
!a.present? ? nil : a.foo

# bad
a.blank? ? nil : a.foo

# bad
!a.blank? ? a.foo : nil

# good
a.presence&.foo

# good
a.present? ? a[1] : nil

# good
a[:key] = value if a.present?

# good
a.present? ? a > 1 : nil
a <= 0 if a.present?

Constant Summary collapse

MSG =
'Use `%<prefer>s` instead of `%<current>s`.'
INDEX_ACCESS_METHODS =
%i[[] []=].freeze

Instance Method Summary collapse

Instance Method Details

#on_if(node) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/rubocop/cop/rails/presence.rb', line 103

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_receiver_and_chain(node) do |receiver, chain|
    return if ignore_chain_node?(chain) || receiver.nil?

    register_chain_offense(node, receiver, chain)
  end
end