Class: RuboCop::Cop::Rails::Blank

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

Overview

Checks for code that can be written with simpler conditionals using ‘Object#blank?` defined by Active Support.

Interaction with ‘Style/UnlessElse`: The configuration of `NotPresent` will not produce an offense in the context of `unless else` if `Style/UnlessElse` is enabled. This is to prevent interference between the autocorrection of the two cops.

Examples:

NilOrEmpty: true (default)

# Converts usages of `nil? || empty?` to `blank?`

# bad
foo.nil? || foo.empty?
foo == nil || foo.empty?

# good
foo.blank?

NotPresent: true (default)

# Converts usages of `!present?` to `blank?`

# bad
!foo.present?

# good
foo.blank?

UnlessPresent: true (default)

# Converts usages of `unless present?` to `if blank?`

# bad
something unless foo.present?

# good
something if foo.blank?

# bad
unless foo.present?
  something
end

# good
if foo.blank?
  something
end

# good
def blank?
  !present?
end

Constant Summary collapse

MSG_NIL_OR_EMPTY =
'Use `%<prefer>s` instead of `%<current>s`.'
MSG_NOT_PRESENT =
'Use `%<prefer>s` instead of `%<current>s`.'
MSG_UNLESS_PRESENT =
'Use `if %<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND =
%i[!].freeze

Instance Method Summary collapse

Instance Method Details

#on_if(node) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/rubocop/cop/rails/blank.rb', line 123

def on_if(node)
  return unless cop_config['UnlessPresent']
  return unless node.unless?
  return if node.else? && config.for_cop('Style/UnlessElse')['Enabled']

  unless_present?(node) do |method_call, receiver|
    range = unless_condition(node, method_call)

    message = format(MSG_UNLESS_PRESENT, prefer: replacement(receiver), current: range.source)
    add_offense(range, message: message) do |corrector|
      autocorrect(corrector, node)
    end
  end
end

#on_or(node) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/rubocop/cop/rails/blank.rb', line 110

def on_or(node)
  return unless cop_config['NilOrEmpty']

  nil_or_empty?(node) do |var1, var2|
    return unless var1 == var2

    message = format(MSG_NIL_OR_EMPTY, prefer: replacement(var1), current: node.source)
    add_offense(node, message: message) do |corrector|
      autocorrect(corrector, node)
    end
  end
end

#on_send(node) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/rubocop/cop/rails/blank.rb', line 96

def on_send(node)
  return unless cop_config['NotPresent']

  not_present?(node) do |receiver|
    # accepts !present? if its in the body of a `blank?` method
    next if defining_blank?(node.parent)

    message = format(MSG_NOT_PRESENT, prefer: replacement(receiver), current: node.source)
    add_offense(node, message: message) do |corrector|
      autocorrect(corrector, node)
    end
  end
end