Sha256: 7a2ee9cee9b9e511a68d788ed37fdb90d1af04b0ddd38f69e6d830201ed06ccd

Contents?: true

Size: 1.7 KB

Versions: 3

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module ThreadSafety
      # Avoid mutating class and module attributes.
      #
      # They are implemented by class variables, which are not thread-safe.
      #
      # @example
      #   # bad
      #   class User
      #     cattr_accessor :current_user
      #   end
      class ClassAndModuleAttributes < Cop
        MSG = 'Avoid mutating class and module attributes.'

        def_node_matcher :mattr?, <<~MATCHER
          (send nil?
            {:mattr_writer :mattr_accessor :cattr_writer :cattr_accessor}
            ...)
        MATCHER

        def_node_matcher :attr?, <<~MATCHER
          (send nil?
            {:attr :attr_accessor :attr_writer}
            ...)
        MATCHER

        def_node_matcher :attr_internal?, <<~MATCHER
          (send nil?
            {:attr_internal :attr_internal_accessor :attr_internal_writer}
            ...)
        MATCHER

        def_node_matcher :class_attr?, <<~MATCHER
          (send nil?
            :class_attribute
            ...)
        MATCHER

        def on_send(node)
          return unless mattr?(node) || class_attr?(node) ||
                        singleton_attr?(node)

          add_offense(node, message: MSG)
        end

        private

        def singleton_attr?(node)
          (attr?(node) || attr_internal?(node)) &&
            defined_in_singleton_class?(node)
        end

        def defined_in_singleton_class?(node)
          node.ancestors.each do |ancestor|
            case ancestor.type
            when :def then return false
            when :sclass then return true
            else next
            end
          end

          false
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubocop-thread_safety-0.4.4 lib/rubocop/cop/thread_safety/class_and_module_attributes.rb
rubocop-thread_safety-0.4.3 lib/rubocop/cop/thread_safety/class_and_module_attributes.rb
rubocop-thread_safety-0.4.2 lib/rubocop/cop/thread_safety/class_and_module_attributes.rb