Sha256: 9ee56f32f6a5f06cf7484765e1f5716766265f1a3cc4055f3bfae32d57afc654

Contents?: true

Size: 835 Bytes

Versions: 5

Compression:

Stored size: 835 Bytes

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks whether some constant value isn't a
      # mutable literal (e.g. array or hash).
      #
      # @example
      #   # bad
      #   CONST = [1, 2, 3]
      #
      #   # good
      #   CONST = [1, 2, 3].freeze
      class MutableConstant < Cop
        MSG = 'Freeze mutable objects assigned to constants.'

        MUTABLE_TYPES = [:array, :hash, :str, :dstr].freeze

        def on_casgn(node)
          _scope, _const_name, value = *node

          return if value && !MUTABLE_TYPES.include?(value.type)

          add_offense(value, :expression)
        end

        def autocorrect(node)
          expr = node.loc.expression
          ->(corrector) { corrector.replace(expr, "#{expr.source}.freeze") }
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rubocop-0.35.1 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.35.0 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.34.2 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.34.1 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.34.0 lib/rubocop/cop/style/mutable_constant.rb