class RuboCop::Cop::Style::RedundantFreeze

Check for uses of ‘Object#freeze` on immutable objects.

NOTE: Regexp and Range literals are frozen objects since Ruby 3.0.

NOTE: From Ruby 3.0, this cop allows explicit freezing of interpolated string literals when ‘# frozen-string-literal: true` is used.

@example

# bad
CONST = 1.freeze

# good
CONST = 1

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/style/redundant_freeze.rb, line 26
def on_send(node)
  return unless node.receiver &&
                (immutable_literal?(node.receiver) ||
                 operation_produces_immutable_object?(node.receiver))

  add_offense(node) do |corrector|
    corrector.remove(node.loc.dot)
    corrector.remove(node.loc.selector)
  end
end

Private Instance Methods

immutable_literal?(node) click to toggle source
# File lib/rubocop/cop/style/redundant_freeze.rb, line 39
def immutable_literal?(node)
  node = strip_parenthesis(node)

  return true if node.immutable_literal?
  return true if frozen_string_literal?(node)

  target_ruby_version >= 3.0 && (node.regexp_type? || node.range_type?)
end
strip_parenthesis(node) click to toggle source
# File lib/rubocop/cop/style/redundant_freeze.rb, line 48
def strip_parenthesis(node)
  if node.begin_type? && node.children.first
    node.children.first
  else
    node
  end
end