Sha256: 4b1ae25a8b8c48a861ff6bf50e67733bb4c2028557f7f6a1892c50be9d9d2dd1

Contents?: true

Size: 1.61 KB

Versions: 12

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

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
      #
      #   # good
      #   CONST = <<~TESTING.freeze
      #   This is a heredoc
      #   TESTING
      class MutableConstant < Cop
        include FrozenStringLiteral

        MSG = 'Freeze mutable objects assigned to constants.'.freeze

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

        def on_or_asgn(node)
          lhs, value = *node

          return unless lhs && lhs.casgn_type?

          on_assignment(value)
        end

        def autocorrect(node)
          expr = node.source_range

          lambda do |corrector|
            if node.array_type? && !node.bracketed?
              corrector.insert_before(expr, '[')
              corrector.insert_after(expr, '].freeze')
            else
              corrector.insert_after(expr, '.freeze')
            end
          end
        end

        private

        def on_assignment(value)
          value = splat_value(value) if splat_value(value)

          return unless value && value.mutable_literal?
          return if FROZEN_STRING_LITERAL_TYPES.include?(value.type) &&
                    frozen_string_literals_enabled?

          add_offense(value)
        end

        def_node_matcher :splat_value, <<-PATTERN
          (array (splat $_))
        PATTERN
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
rubocop-0.59.2 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.59.1 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.59.0 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.58.2 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.58.1 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.58.0 lib/rubocop/cop/style/mutable_constant.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.57.2 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.57.1 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.57.0 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.56.0 lib/rubocop/cop/style/mutable_constant.rb
rubocop-0.55.0 lib/rubocop/cop/style/mutable_constant.rb