Sha256: 12b461dd23b3e0bef9ac62e4b3cee45196d04c6235f82e1ce0c5394556602f07

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

require 'set'
require_relative 'base_detector'

module Reek
  module SmellDetectors
    #
    # Class variables form part of the global runtime state, and as such make
    # it easy for one part of the system to accidentally or inadvertently
    # depend on another part of the system. So the system becomes more prone to
    # problems where changing something over here breaks something over there.
    # In particular, class variables can make it hard to set up tests (because
    # the context of the test includes all global state).
    #
    # See {file:docs/Class-Variable.md} for details.
    class ClassVariable < BaseDetector
      def self.contexts # :nodoc:
        [:class, :module]
      end

      #
      # Checks whether the given class or module declares any class variables.
      #
      # @return [Array<SmellWarning>]
      #
      def sniff
        class_variables_in_context.map do |variable, lines|
          smell_warning(
            context: context,
            lines: lines,
            message: "declares the class variable '#{variable}'",
            parameters: { name: variable.to_s })
        end
      end

      #
      # Collects the names of the class variables declared and/or used
      # in the given module.
      #
      # :reek:TooManyStatements: { max_statements: 7 }
      def class_variables_in_context
        result = Hash.new { |hash, key| hash[key] = [] }
        collector = proc do |cvar_node|
          result[cvar_node.name].push(cvar_node.line)
        end
        [:cvar, :cvasgn, :cvdecl].each do |stmt_type|
          expression.each_node(stmt_type, [:class, :module], &collector)
        end
        result
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
reek-4.7.3 lib/reek/smell_detectors/class_variable.rb