Class: RuboCop::Cop::Rails::CompactBlank

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

Overview

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 { |_k, 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 =
%i[reject delete_if reject!].freeze

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#on_send(node) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/rubocop/cop/rails/compact_blank.rb', line 64

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