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? }
collection.select(&:present?)
collection.select { |_k, v| v.present? }
collection.filter(&:present?)
collection.filter { |_k, v| v.present? }

# 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.keep_if(&:present?)            # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!`
collection.keep_if { |_k, v| v.present? } # Same behavior as `Array#compact_blank!` and `Hash#compact_blank!`

# good
collection.compact_blank!

Constant Summary collapse

MSG =
'Use `%<preferred_method>s` instead.'
RESTRICT_ON_SEND =
%i[reject delete_if select filter keep_if].freeze
DESTRUCTIVE_METHODS =
%i[delete_if keep_if].freeze

Constants included from TargetRailsVersion

TargetRailsVersion::TARGET_GEM_NAME, TargetRailsVersion::USES_REQUIRES_GEM_API

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#on_send(node) ⇒ Object



82
83
84
85
86
87
88
89
90
91
# File 'lib/rubocop/cop/rails/compact_blank.rb', line 82

def on_send(node)
  return if target_ruby_version < 2.6 && node.method?(:filter)
  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