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

Inherits:
RuboCop::Cop show all
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/presence.rb

Overview

This cop 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

#autocorrect(node) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/rubocop/cop/rails/presence.rb', line 87

def autocorrect(node)
  lambda do |corrector|
    redundant_receiver_and_other(node) do |receiver, other|
      corrector.replace(node.source_range, replacement(receiver, other))
    end

    redundant_negative_receiver_and_other(node) do |receiver, other|
      corrector.replace(node.source_range, replacement(receiver, other))
    end
  end
end

#on_if(node) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rubocop/cop/rails/presence.rb', line 75

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

  redundant_receiver_and_other(node) do |receiver, other|
    add_offense(node, message: message(node, receiver, other)) unless ignore_other_node?(other) || receiver.nil?
  end

  redundant_negative_receiver_and_other(node) do |receiver, other|
    add_offense(node, message: message(node, receiver, other)) unless ignore_other_node?(other) || receiver.nil?
  end
end