Class: RuboCop::Cop::Homebrew::CompactBlank

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
rubocops/compact_blank.rb

Overview

Note:

It is unsafe by default because false positives may occur in the blank check of block arguments to the receiver object.

For example, [[1, 2], [3, nil]].reject { |first, second| second.blank? } and [[1, 2], [3, nil]].compact_blank are not compatible. The same is true for blank?. This will work fine when the receiver is a hash object.

And compact_blank! has different implementations for Array, Hash, and ActionController::Parameters. Array#compact_blank!, Hash#compact_blank! are equivalent to delete_if(&:blank?). ActionController::Parameters#compact_blank! is equivalent to reject!(&:blank?). If the cop makes a mistake, autocorrected code may get unexpected behavior.

Checks if collection can be blank-compacted with compact_blank.

Examples:


# bad
collection.reject(&:blank?)
collection.reject { |_k, v| v.blank? }

# good
collection.compact_blank

# bad
collection.delete_if(&:blank?)           # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!`
collection.delete_if { |_, v| v.blank? } # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!`
collection.reject!(&:blank?)             # Same behavior as `ActionController::Parameters#compact_blank!`
collection.reject! { |_k, v| v.blank? }  # Same behavior as `ActionController::Parameters#compact_blank!`

# good
collection.compact_blank!

Constant Summary collapse

MSG =
"Use `%<preferred_method>s` instead."
RESTRICT_ON_SEND =
[:reject, :delete_if, :reject!].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'rubocops/compact_blank.rb', line 62

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

  range = offense_range(node)
  preferred_method = preferred_method(node)
  add_offense(range, message: format(MSG, preferred_method: preferred_method)) do |corrector|
    corrector.replace(range, preferred_method)
  end
end