123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Base

Relationships & Source Files
Namespace Children
Classes:
Extension / Inclusion / Inheritance Descendants
Subclasses:
Cop, RuboCop::Cop::Bundler::DuplicatedGem, RuboCop::Cop::Bundler::DuplicatedGroup, RuboCop::Cop::Bundler::GemComment, RuboCop::Cop::Bundler::GemFilename, RuboCop::Cop::Bundler::GemVersion, RuboCop::Cop::Bundler::InsecureProtocolSource, RuboCop::Cop::Bundler::OrderedGems, Gemspec::AddRuntimeDependency, Gemspec::DependencyVersion, Gemspec::DeprecatedAttributeAssignment, Gemspec::DevelopmentDependencies, Gemspec::DuplicatedAssignment, Gemspec::OrderedDependencies, Gemspec::RequireMFA, Gemspec::RequiredRubyVersion, Gemspec::RubyVersionGlobalsUsage, InternalAffairs::CopDescription, InternalAffairs::CreateEmptyFile, InternalAffairs::EmptyLineBetweenExpectOffenseAndCorrection, InternalAffairs::ExampleDescription, InternalAffairs::ExampleHeredocDelimiter, InternalAffairs::InheritDeprecatedCopClass, InternalAffairs::LambdaOrProc, InternalAffairs::LocationExpression, InternalAffairs::LocationLineEqualityComparison, InternalAffairs::MethodNameEndWith, InternalAffairs::MethodNameEqual, InternalAffairs::NodeDestructuring, InternalAffairs::NodeFirstOrLastArgument, InternalAffairs::NodeMatcherDirective, InternalAffairs::NodeTypePredicate, InternalAffairs::NumblockHandler, InternalAffairs::OffenseLocationKeyword, InternalAffairs::ProcessedSourceBufferName, InternalAffairs::RedundantContextConfigParameter, InternalAffairs::RedundantDescribedClassAsSubject, InternalAffairs::RedundantExpectOffenseArguments, InternalAffairs::RedundantLetRuboCopConfigNew, InternalAffairs::RedundantLocationArgument, InternalAffairs::RedundantMessageArgument, InternalAffairs::RedundantMethodDispatchNode, InternalAffairs::RedundantSourceRange, InternalAffairs::SingleLineComparison, InternalAffairs::StyleDetectedApiUse, InternalAffairs::UndefinedConfig, InternalAffairs::UselessMessageAssertion, InternalAffairs::UselessRestrictOnSend, Layout::AccessModifierIndentation, Layout::ArgumentAlignment, Layout::ArrayAlignment, Layout::AssignmentIndentation, Layout::BeginEndAlignment, Layout::BlockAlignment, Layout::BlockEndNewline, Layout::CaseIndentation, Layout::ClassStructure, Layout::ClosingHeredocIndentation, Layout::ClosingParenthesisIndentation, Layout::CommentIndentation, Layout::ConditionPosition, Layout::DefEndAlignment, Layout::DotPosition, Layout::ElseAlignment, Layout::EmptyComment, Layout::EmptyLineAfterGuardClause, Layout::EmptyLineAfterMagicComment, Layout::EmptyLineAfterMultilineCondition, Layout::EmptyLineBetweenDefs, Layout::EmptyLines, Layout::EmptyLinesAroundAccessModifier, Layout::EmptyLinesAroundArguments, Layout::EmptyLinesAroundAttributeAccessor, Layout::EmptyLinesAroundBeginBody, Layout::EmptyLinesAroundBlockBody, Layout::EmptyLinesAroundClassBody, Layout::EmptyLinesAroundExceptionHandlingKeywords, Layout::EmptyLinesAroundMethodBody, Layout::EmptyLinesAroundModuleBody, Layout::EndAlignment, Layout::EndOfLine, Layout::ExtraSpacing, Layout::FirstArgumentIndentation, Layout::FirstArrayElementIndentation, Layout::FirstArrayElementLineBreak, Layout::FirstHashElementIndentation, Layout::FirstHashElementLineBreak, Layout::FirstMethodArgumentLineBreak, Layout::FirstMethodParameterLineBreak, Layout::FirstParameterIndentation, Layout::HashAlignment, Layout::HeredocArgumentClosingParenthesis, Layout::HeredocIndentation, Layout::IndentationConsistency, Layout::IndentationStyle, Layout::IndentationWidth, Layout::InitialIndentation, Layout::LeadingCommentSpace, Layout::LeadingEmptyLines, Layout::LineContinuationLeadingSpace, Layout::LineContinuationSpacing, Layout::LineEndStringConcatenationIndentation, Layout::LineLength, Layout::MultilineArrayBraceLayout, Layout::MultilineArrayLineBreaks, Layout::MultilineAssignmentLayout, Layout::MultilineBlockLayout, Layout::MultilineHashBraceLayout, Layout::MultilineHashKeyLineBreaks, Layout::MultilineMethodArgumentLineBreaks, Layout::MultilineMethodCallBraceLayout, Layout::MultilineMethodCallIndentation, Layout::MultilineMethodDefinitionBraceLayout, Layout::MultilineMethodParameterLineBreaks, Layout::MultilineOperationIndentation, Layout::ParameterAlignment, Layout::RedundantLineBreak, Layout::RescueEnsureAlignment, Layout::SingleLineBlockChain, Layout::SpaceAfterColon, Layout::SpaceAfterComma, Layout::SpaceAfterMethodName, Layout::SpaceAfterNot, Layout::SpaceAfterSemicolon, Layout::SpaceAroundBlockParameters, Layout::SpaceAroundEqualsInParameterDefault, Layout::SpaceAroundKeyword, Layout::SpaceAroundMethodCallOperator, Layout::SpaceAroundOperators, Layout::SpaceBeforeBlockBraces, Layout::SpaceBeforeBrackets, Layout::SpaceBeforeComma, Layout::SpaceBeforeComment, Layout::SpaceBeforeFirstArg, Layout::SpaceBeforeSemicolon, Layout::SpaceInLambdaLiteral, Layout::SpaceInsideArrayLiteralBrackets, Layout::SpaceInsideArrayPercentLiteral, Layout::SpaceInsideBlockBraces, Layout::SpaceInsideHashLiteralBraces, Layout::SpaceInsideParens, Layout::SpaceInsidePercentLiteralDelimiters, Layout::SpaceInsideRangeLiteral, Layout::SpaceInsideReferenceBrackets, Layout::SpaceInsideStringInterpolation, Layout::TrailingEmptyLines, Layout::TrailingWhitespace, Lint::AmbiguousAssignment, Lint::AmbiguousBlockAssociation, Lint::AmbiguousOperator, Lint::AmbiguousOperatorPrecedence, Lint::AmbiguousRange, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BigDecimalNew, Lint::BinaryOperatorWithIdenticalOperands, Lint::BooleanSymbol, Lint::CircularArgumentReference, Lint::ConstantDefinitionInBlock, Lint::ConstantOverwrittenInRescue, Lint::ConstantResolution, Lint::Debugger, Lint::DeprecatedClassMethods, Lint::DeprecatedConstants, Lint::DeprecatedOpenSSLConstant, Lint::DisjunctiveAssignmentInConstructor, Lint::DuplicateBranch, Lint::DuplicateCaseCondition, Lint::DuplicateElsifCondition, Lint::DuplicateHashKey, Lint::DuplicateMagicComment, Lint::DuplicateMatchPattern, Lint::DuplicateMethods, Lint::DuplicateRegexpCharacterClassElement, Lint::DuplicateRequire, Lint::DuplicateRescueException, Lint::DuplicateSetElement, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyBlock, Lint::EmptyClass, Lint::EmptyConditionalBody, Lint::EmptyEnsure, Lint::EmptyExpression, Lint::EmptyFile, Lint::EmptyInPattern, Lint::EmptyInterpolation, Lint::EmptyWhen, Lint::EnsureReturn, Lint::ErbNewArguments, Lint::FlipFlop, Lint::FloatComparison, Lint::FloatOutOfRange, Lint::FormatParameterMismatch, Lint::HashCompareByIdentity, Lint::HeredocMethodCallPosition, Lint::IdentityComparison, Lint::ImplicitStringConcatenation, Lint::IncompatibleIoSelectWithFiberScheduler, Lint::IneffectiveAccessModifier, Lint::InheritException, Lint::InterpolationCheck, Lint::ItWithoutArgumentsInBlock, Lint::LambdaWithoutLiteralBlock, Lint::LiteralAsCondition, Lint::LiteralAssignmentInCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::MissingCopEnableDirective, Lint::MissingSuper, Lint::MixedCaseRange, Lint::MixedRegexpCaptureTypes, Lint::MultipleComparison, Lint::NestedMethodDefinition, Lint::NestedPercentLiteral, Lint::NextWithoutAccumulator, Lint::NoReturnInBeginEndBlocks, Lint::NonAtomicFileOperation, Lint::NonDeterministicRequireOrder, Lint::NonLocalExitFromIterator, Lint::NumberConversion, Lint::NumberedParameterAssignment, Lint::OrAssignmentToConstant, Lint::OrderedMagicComments, Lint::OutOfRangeRegexpRef, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RaiseException, Lint::RandOne, Lint::RedundantCopDisableDirective, Lint::RedundantCopEnableDirective, Lint::RedundantDirGlobSort, Lint::RedundantRegexpQuantifiers, Lint::RedundantRequireStatement, Lint::RedundantSafeNavigation, Lint::RedundantSplatExpansion, Lint::RedundantStringCoercion, Lint::RedundantWithIndex, Lint::RedundantWithObject, Lint::RefinementImportMethods, Lint::RegexpAsCondition, Lint::RequireParentheses, Lint::RequireRangeParentheses, Lint::RequireRelativeSelfPath, Lint::RescueException, Lint::RescueType, Lint::ReturnInVoidContext, Lint::SafeNavigationChain, Lint::SafeNavigationConsistency, Lint::SafeNavigationWithEmpty, Lint::ScriptPermission, Lint::SelfAssignment, Lint::SendWithMixinArgument, Lint::ShadowedArgument, Lint::ShadowedException, Lint::ShadowingOuterLocalVariable, Lint::StructNewOverride, Lint::SuppressedException, Lint::SymbolConversion, Lint::Syntax, Lint::ToEnumArguments, Lint::ToJSON, Lint::TopLevelReturnWithArgument, Lint::TrailingCommaInAttributeDeclaration, Lint::TripleQuotes, Lint::UnderscorePrefixedVariableName, Lint::UnescapedBracketInRegexp, Lint::UnexpectedBlockArity, Lint::UnifiedInteger, Lint::UnmodifiedReduceAccumulator, Lint::UnreachableCode, Lint::UnreachableLoop, Lint::UnusedBlockArgument, Lint::UnusedMethodArgument, Lint::UriEscapeUnescape, Lint::UriRegexp, Lint::UselessAccessModifier, Lint::UselessAssignment, Lint::UselessElseWithoutRescue, Lint::UselessMethodDefinition, Lint::UselessNumericOperation, Lint::UselessRescue, Lint::UselessRuby2Keywords, Lint::UselessSetterCall, Lint::UselessTimes, Lint::Void, Metrics::AbcSize, Metrics::BlockLength, Metrics::BlockNesting, Metrics::ClassLength, Metrics::CollectionLiteralLength, Metrics::CyclomaticComplexity, Metrics::MethodLength, Metrics::ModuleLength, Metrics::ParameterLists, Metrics::PerceivedComplexity, Migration::DepartmentName, Naming::AccessorMethodName, Naming::AsciiIdentifiers, Naming::BinaryOperatorParameterName, Naming::BlockForwarding, Naming::BlockParameterName, Naming::ClassAndModuleCamelCase, Naming::ConstantName, Naming::FileName, Naming::HeredocDelimiterCase, Naming::HeredocDelimiterNaming, Naming::InclusiveLanguage, Naming::MemoizedInstanceVariableName, Naming::MethodName, Naming::MethodParameterName, Naming::PredicateName, Naming::RescuedExceptionsVariableName, Naming::VariableName, Naming::VariableNumber, Security::CompoundHash, Security::Eval, Security::IoMethods, Security::JSONLoad, Security::MarshalLoad, Security::Open, Security::YAMLLoad, Style::AccessModifierDeclarations, Style::AccessorGrouping, Style::Alias, Style::AmbiguousEndlessMethodDefinition, Style::AndOr, Style::ArgumentsForwarding, Style::ArrayCoercion, Style::ArrayFirstLast, Style::ArrayIntersect, Style::ArrayJoin, Style::AsciiComments, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BisectedAttrAccessor, Style::BitwisePredicate, Style::BlockComments, Style::BlockDelimiters, Style::CaseEquality, Style::CaseLikeIf, Style::CharacterLiteral, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassEqualityComparison, Style::ClassMethods, Style::ClassMethodsDefinitions, Style::ClassVars, Style::CollectionCompact, Style::CollectionMethods, Style::ColonMethodCall, Style::ColonMethodDefinition, Style::CombinableDefined, Style::CombinableLoops, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentedKeyword, Style::ComparableClamp, Style::ConcatArrayLiterals, Style::ConditionalAssignment, Style::ConstantVisibility, Style::Copyright, Style::DataInheritance, Style::DateTime, Style::DefWithParentheses, Style::Dir, Style::DirEmpty, Style::DisableCopsWithinSourceCodeDirective, Style::DocumentDynamicEvalDefinition, Style::Documentation, Style::DocumentationMethod, Style::DoubleCopDisableDirective, Style::DoubleNegation, Style::EachForSimpleLoop, Style::EachWithObject, Style::EmptyBlockParameter, Style::EmptyCaseCondition, Style::EmptyElse, Style::EmptyHeredoc, Style::EmptyLambdaParameter, Style::EmptyLiteral, Style::EmptyMethod, Style::Encoding, Style::EndBlock, Style::EndlessMethod, Style::EnvHome, Style::EvalWithLocation, Style::EvenOdd, Style::ExactRegexpMatch, Style::ExpandPathArguments, Style::ExplicitBlockArgument, Style::ExponentialNotation, Style::FetchEnvVar, Style::FileEmpty, Style::FileRead, Style::FileWrite, Style::FloatDivision, Style::For, Style::FormatString, Style::FormatStringToken, Style::FrozenStringLiteralComment, Style::GlobalStdStream, Style::GlobalVars, Style::GuardClause, Style::HashAsLastArrayItem, Style::HashConversion, Style::HashEachMethods, Style::HashExcept, Style::HashLikeCase, Style::HashSyntax, Style::HashTransformKeys, Style::HashTransformValues, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::IfUnlessModifierOfIfUnless, Style::IfWithBooleanLiteralBranches, Style::IfWithSemicolon, Style::ImplicitRuntimeError, Style::InPatternThen, Style::InfiniteLoop, Style::InlineComment, Style::InverseMethods, Style::InvertibleUnlessCondition, Style::IpAddresses, Style::KeywordArgumentsMerging, Style::KeywordParametersOrder, Style::Lambda, Style::LambdaCall, Style::LineEndConcatenation, Style::MagicCommentFormat, Style::MapCompactWithConditionalBlock, Style::MapIntoArray, Style::MapToHash, Style::MapToSet, Style::MethodCallWithArgsParentheses, Style::MethodCallWithoutArgsParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MinMax, Style::MinMaxComparison, Style::MissingElse, Style::MissingRespondToMissing, Style::MixinGrouping, Style::MixinUsage, Style::ModuleFunction, Style::MultilineBlockChain, Style::MultilineIfModifier, Style::MultilineIfThen, Style::MultilineInPatternThen, Style::MultilineMemoization, Style::MultilineMethodSignature, Style::MultilineTernaryOperator, Style::MultilineWhenThen, Style::MultipleComparison, Style::MutableConstant, Style::NegatedIf, Style::NegatedIfElseCondition, Style::NegatedUnless, Style::NegatedWhile, Style::NestedFileDirname, Style::NestedModifier, Style::NestedParenthesizedCalls, Style::NestedTernaryOperator, Style::Next, Style::NilComparison, Style::NilLambda, Style::NonNilCheck, Style::Not, Style::NumberedParameters, Style::NumberedParametersLimit, Style::NumericLiteralPrefix, Style::NumericLiterals, Style::NumericPredicate, Style::ObjectThen, Style::OneLineConditional, Style::OpenStructUse, Style::OperatorMethodCall, Style::OptionHash, Style::OptionalArguments, Style::OptionalBooleanParameter, Style::OrAssignment, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PreferredHashMethods, Style::Proc, Style::QuotedSymbols, Style::RaiseArgs, Style::RandomWithOffset, Style::RedundantArgument, Style::RedundantArrayConstructor, Style::RedundantAssignment, Style::RedundantBegin, Style::RedundantCapitalW, Style::RedundantCondition, Style::RedundantConditional, Style::RedundantConstantBase, Style::RedundantCurrentDirectoryInPath, Style::RedundantDoubleSplatHashBraces, Style::RedundantEach, Style::RedundantException, Style::RedundantFetchBlock, Style::RedundantFileExtensionInRequire, Style::RedundantFilterChain, Style::RedundantFreeze, Style::RedundantHeredocDelimiterQuotes, Style::RedundantInitialize, Style::RedundantInterpolation, Style::RedundantInterpolationUnfreeze, Style::RedundantLineContinuation, Style::RedundantParentheses, Style::RedundantPercentQ, Style::RedundantRegexpArgument, Style::RedundantRegexpCharacterClass, Style::RedundantRegexpConstructor, Style::RedundantRegexpEscape, Style::RedundantReturn, Style::RedundantSelf, Style::RedundantSelfAssignment, Style::RedundantSelfAssignmentBranch, Style::RedundantSort, Style::RedundantSortBy, Style::RedundantStringEscape, Style::RegexpLiteral, Style::RequireOrder, Style::RescueModifier, Style::RescueStandardError, Style::ReturnNil, Style::ReturnNilInPredicateMethodDefinition, Style::SafeNavigation, Style::SafeNavigationChainLength, Style::Sample, Style::SelectByRegexp, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SendWithLiteralMethodName, Style::SignalException, Style::SingleArgumentDig, Style::SingleLineBlockParams, Style::SingleLineDoEndBlock, Style::SingleLineMethods, Style::SlicingWithRange, Style::SoleNestedConditional, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StaticClass, Style::StderrPuts, Style::StringChars, Style::StringConcatenation, Style::StringHashKeys, Style::StringLiterals, Style::StringLiteralsInInterpolation, Style::StringMethods, Style::Strip, Style::StructInheritance, Style::SuperArguments, Style::SuperWithArgsParentheses, Style::SwapValues, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::TernaryParentheses, Style::TopLevelMethodDefinition, Style::TrailingBodyOnClass, Style::TrailingBodyOnMethodDefinition, Style::TrailingBodyOnModule, Style::TrailingCommaInArguments, Style::TrailingCommaInArrayLiteral, Style::TrailingCommaInBlockArgs, Style::TrailingCommaInHashLiteral, Style::TrailingMethodEndStatement, Style::TrailingUnderscoreVariable, Style::TrivialAccessors, Style::UnlessElse, Style::UnlessLogicalOperators, Style::UnpackFirst, Style::VariableInterpolation, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray, Style::YAMLFileRead, Style::YodaCondition, Style::YodaExpression, Style::ZeroLengthPredicate
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
self, AutocorrectLogic, IgnoredNode, ::RuboCop::Util, RuboCop::AST::Sexp
Inherits: Object
Defined in: lib/rubocop/cop/base.rb

Overview

A scaffold for concrete cops.

The Cop::Base class is meant to be extended.

Cops track offenses and can autocorrect them on the fly.

A commissioner object is responsible for traversing the AST and invoking the specific callbacks on each cop.

First the callback #on_new_investigation is called; if a cop needs to do its own processing of the AST or depends on something else.

Then callbacks like on_def, on_send (see AST::Traversal) are called with their respective nodes.

Finally the callback #on_investigation_end is called.

Within these callbacks, cops are meant to call #add_offense or #add_global_offense. Use the #processed_source method to get the currently processed source being investigated.

In case of invalid syntax / unparsable content, the callback #on_other_file is called instead of all the other on_…​ callbacks.

Private methods are not meant for custom cops consumption, nor are any instance variables.

Constant Summary

Class Attribute Summary

Class Method Summary

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

AutocorrectLogic - Included

IgnoredNode - Included

Constructor Details

.new(config = nil, options = nil) ⇒ Base

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 156

def initialize(config = nil, options = nil)
  @config = config || Config.new
  @options = options || { debug: false }
  reset_investigation
end

Class Attribute Details

.gem_requirements (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 138

attr_reader :gem_requirements

.lint?Boolean (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 105

def self.lint?
  department == :Lint
end

.support_autocorrect?Boolean (readonly)

Returns if class supports autocorrect. It is recommended to extend AutoCorrector instead of overriding

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 87

def self.support_autocorrect?
  false
end

.support_multiple_source?Boolean (readonly)

Override if your cop should be called repeatedly for multiple investigations Between calls to #on_new_investigation and #on_investigation_end, the result of #processed_source will remain constant. You should invalidate any caches that depend on the current #processed_source in the #on_new_investigation callback. If your cop does autocorrections, be aware that your instance may be called multiple times with the same processed_source.path but different content.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 129

def self.support_multiple_source?
  false
end

Class Method Details

.autocorrect_incompatible_withArray<Base>

List of cops that should not try to autocorrect at the same time as this cop

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 59

def self.autocorrect_incompatible_with
  []
end

.badge

Naming

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 93

def self.badge
  @badge ||= Badge.for(name)
end

.callbacks_needed

This method is for internal use only.
[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 323

def self.callbacks_needed
  @callbacks_needed ||= public_instance_methods.select do |m|
    # OPTIMIZE: Check method existence first to make fewer `start_with?` calls.
    # At the time of writing this comment, this excludes 98 of ~104 methods.
    # `start_with?` with two string arguments instead of a regex is faster
    # in this specific case as well.
    !Base.method_defined?(m) && # exclude standard "callbacks" like 'on_begin_investigation'
      m.start_with?('on_', 'after_')
  end
end

.cop_name

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 97

def self.cop_name
  badge.to_s
end

.department

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 101

def self.department
  badge.department
end

.documentation_url(config = nil) ⇒ String?

Returns an url to view this cops documentation online. Requires 'DocumentationBaseURL' to be set for your department. Will follow the convention of RuboCops own documentation structure, overwrite this method to accommodate your custom layout.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 70

def self.documentation_url(config = nil)
  Documentation.url_for(self, config)
end

.exclude_from_registry

Call for abstract Cop classes

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 81

def self.exclude_from_registry
  Registry.global.dismiss(self)
end

.inherited(subclass)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 74

def self.inherited(subclass)
  super
  subclass.instance_variable_set(:@gem_requirements, gem_requirements.dup)
  Registry.global.enlist(subclass)
end

.joining_forces

Override and return the Force class(es) you need to join

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 118

def self.joining_forces; end

.match?(given_names) ⇒ Boolean

Returns true if the cop name or the cop namespace matches any of the given names.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 111

def self.match?(given_names)
  return false unless given_names

  given_names.include?(cop_name) || given_names.include?(badge.department_name)
end

.requires_gem(gem_name, *version_requirements)

Register a version requirement for the given gem name. This cop will be skipped unless the target satisfies all requirements.

Parameters:

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 151

def requires_gem(gem_name, *version_requirements)
  @gem_requirements[gem_name] = Gem::Requirement.new(version_requirements)
end

.restrict_on_send (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 395

private_class_method def self.restrict_on_send
  @restrict_on_send ||= self::RESTRICT_ON_SEND.to_a.freeze
end

Instance Attribute Details

#active_support_extensions_enabled?Boolean (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 272

def active_support_extensions_enabled?
  @config.active_support_extensions_enabled?
end

#always_autocorrect?Boolean (readonly)

This method is for internal use only.
[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 351

def always_autocorrect?
  # `true` is the same as `'always'` for backward compatibility.
  ['always', true].include?(cop_config.fetch('AutoCorrect', 'always'))
end

#config (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 43

attr_reader :config, :processed_source

#config_to_allow_offenses (rw)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 252

def config_to_allow_offenses
  Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] ||= {}
end

#config_to_allow_offenses=(hash) (rw)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 256

def config_to_allow_offenses=(hash)
  Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] = hash
end

#contextual_autocorrect?Boolean (readonly)

This method is for internal use only.
[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 357

def contextual_autocorrect?
  cop_config.fetch('AutoCorrect', 'always') == 'contextual'
end

#processed_source (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 43

attr_reader :config, :processed_source

#string_literals_frozen_by_default?Boolean (readonly)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 276

def string_literals_frozen_by_default?
  @config.string_literals_frozen_by_default?
end

#target_satisfies_all_gem_version_requirements?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 528

def target_satisfies_all_gem_version_requirements?
  self.class.gem_requirements.all? do |gem_name, version_req|
    all_gem_versions_in_target = @config.gem_versions_in_target
    next false unless all_gem_versions_in_target

    gem_version_in_target = all_gem_versions_in_target[gem_name]
    next false unless gem_version_in_target

    version_req.satisfied_by?(gem_version_in_target)
  end
end

Instance Method Details

#add_global_offense(message = nil, severity: nil)

Adds an offense that has no particular location. No correction can be applied to global offenses

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 189

def add_global_offense(message = nil, severity: nil)
  severity = find_severity(nil, severity)
  message = find_message(nil, message)
  range = Offense::NO_LOCATION
  status = enabled_line?(range.line) ? :unsupported : :disabled
  current_offenses << Offense.new(severity, range, message, name, status)
end

#add_offense(node_or_range, message: nil, severity: nil, &block)

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense. If message is not specified, the method #message will be called.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 201

def add_offense(node_or_range, message: nil, severity: nil, &block)
  range = range_from_node_or_range(node_or_range)
  return unless current_offense_locations.add?(range)

  range_to_pass = callback_argument(range)

  severity = find_severity(range_to_pass, severity)
  message = find_message(range_to_pass, message)

  status, corrector = enabled_line?(range.line) ? correct(range, &block) : :disabled

  # Since this range may be generated from Ruby code embedded in some
  # template file, we convert it to location info in the original file.
  range = range_for_original(range)

  current_offenses << Offense.new(severity, range, message, name, status, corrector)
end

#annotate(message) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 479

def annotate(message)
  RuboCop::Cop::MessageAnnotator.new(
    config, cop_name, cop_config, @options
  ).annotate(message)
end

#apply_correction(corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 373

def apply_correction(corrector)
  current_corrector&.merge!(corrector) if corrector
end

#attempt_correction(range, corrector) ⇒ Symbol (private)

Returns:

  • (Symbol)

    offense status

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 443

def attempt_correction(range, corrector)
  if corrector
    status = :corrected
  elsif disable_uncorrectable?
    corrector = disable_uncorrectable(range)
    status = :corrected_with_todo
  else
    return :unsupported
  end

  apply_correction(corrector)
  status
end

#begin_investigation(processed_source, offset: 0, original: processed_source)

This method is for internal use only.

Called before any investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 337

def begin_investigation(processed_source, offset: 0, original: processed_source)
  @current_offenses = nil
  @current_offense_locations = nil
  @currently_disabled_lines = nil
  @processed_source = processed_source
  @current_corrector = nil

  # We need to keep track of the original source and offset,
  # because `processed_source` here may be an embedded code in it.
  @current_offset = offset
  @current_original = original
end

#callback_argument(range) (private)

Reserved for Cop::Cop

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 369

def callback_argument(range)
  range
end

#callbacks_needed

This method is for internal use only.
[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 318

def callbacks_needed
  self.class.callbacks_needed
end

#complete_investigation (private)

Called to complete an investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 402

def complete_investigation
  InvestigationReport.new(
    self, processed_source, @current_offenses || EMPTY_OFFENSES, @current_corrector
  )
ensure
  reset_investigation
end

#cop_config

Configuration Helpers

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 246

def cop_config
  # Use department configuration as basis, but let individual cop
  # configuration override.
  @cop_config ||= @config.for_badge(self.class.badge)
end

#cop_name Also known as: #name

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 238

def cop_name
  @cop_name ||= self.class.cop_name
end

#correct(range) ⇒ Symbol, Corrector (private)

Returns:

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 417

def correct(range)
  if block_given?
    corrector = Corrector.new(self)
    yield corrector
    if corrector.empty?
      corrector = nil
    elsif !self.class.support_autocorrect?
      raise "The Cop #{name} must `extend AutoCorrector` to be able to autocorrect"
    end
  end

  [use_corrector(range, corrector), corrector]
end

#current_corrector (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 387

def current_corrector
  @current_corrector ||= Corrector.new(@processed_source) if @processed_source.valid_syntax?
end

#current_offense_locations (private)

Reserved for Commissioner:

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 379

def current_offense_locations
  @current_offense_locations ||= Set.new
end

#current_offenses (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 391

def current_offenses
  @current_offenses ||= []
end

#currently_disabled_lines (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 383

def currently_disabled_lines
  @currently_disabled_lines ||= Set.new
end

#custom_severity (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 507

def custom_severity
  severity = cop_config['Severity']
  return unless severity

  if Severity::NAMES.include?(severity.to_sym)
    severity.to_sym
  else
    message = "Warning: Invalid severity '#{severity}'. " \
              "Valid severities are #{Severity::NAMES.join(', ')}."
    warn(Rainbow(message).red)
  end
end

#default_severity (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 503

def default_severity
  self.class.lint? ? :warning : :convention
end

#disable_uncorrectable(range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 457

def disable_uncorrectable(range)
  line = range.line
  return unless currently_disabled_lines.add?(line)

  disable_offense(range)
end

#enabled_line?(line_number) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 493

def enabled_line?(line_number)
  return true if @options[:ignore_disable_comments] || !@processed_source

  @processed_source.comment_config.cop_enabled_at_line?(self, line_number)
end

#excluded_file?(file) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 289

def excluded_file?(file)
  !relevant_file?(file)
end

#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

(1) the file under inspection
(2) the cop's source code
(3) the config (eg a .rubocop.yml file)

For example, some cops may want to look at other parts of the codebase being inspected to find violations. A cop may use the presence or absence of file foo.rb to determine whether a certain violation exists in bar.rb.

Overriding this method allows the cop to indicate to RuboCop’s ResultCache system when those external dependencies change, ie when the ResultCache should be invalidated.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 234

def external_dependency_checksum
  nil
end

#file_name_matches_any?(file, parameter, default_result) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 485

def file_name_matches_any?(file, parameter, default_result)
  patterns = cop_config[parameter]
  return default_result unless patterns

  patterns = FilePatterns.from(patterns)
  patterns.match?(config.path_relative_to_config(file)) || patterns.match?(file)
end

#find_message(range, message) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 475

def find_message(range, message)
  annotate(message || message(range))
end

#find_severity(_range, severity) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 499

def find_severity(_range, severity)
  custom_severity || severity || default_severity
end

#inspect

This method is for internal use only.
[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 361

def inspect # :nodoc:
  "#<#{self.class.name}:#{object_id} @config=#{@config} @options=#{@options}>"
end

#message(_range = nil)

Gets called if no message is specified when calling #add_offense or #add_global_offense Cops are discouraged to override this; instead pass your message directly

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 183

def message(_range = nil)
  self.class::MSG
end

#name

Alias for #cop_name.

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 242

alias name cop_name

#offenses

Deprecated.

Make potential errors with previous API more obvious

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 309

def offenses
  raise 'The offenses are not directly available; ' \
        'they are returned as the result of the investigation'
end

#on_investigation_end

Called after all on_…​ have been called When refining this method, always call super

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 170

def on_investigation_end
  # Typically do nothing here
end

#on_new_investigation

Called before all on_…​ have been called When refining this method, always call super

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 164

def on_new_investigation
  # Typically do nothing here
end

#on_other_file

Called instead of all on_…​ callbacks for unrecognized files / syntax errors When refining this method, always call super

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 176

def on_other_file
  # Typically do nothing here
end

#parse(source, path = nil)

There should be very limited reasons for a Cop to do it’s own parsing

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 294

def parse(source, path = nil)
  ProcessedSource.new(source, target_ruby_version, path, parser_engine: parser_engine)
end

#parser_engine

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 264

def parser_engine
  @config.parser_engine
end

#range_for_original(range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 520

def range_for_original(range)
  ::Parser::Source::Range.new(
    @current_original.buffer,
    range.begin_pos + @current_offset,
    range.end_pos + @current_offset
  )
end

#range_from_node_or_range(node_or_range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 464

def range_from_node_or_range(node_or_range)
  if node_or_range.respond_to?(:loc)
    node_or_range.source_range
  elsif node_or_range.is_a?(::Parser::Source::Range)
    node_or_range
  else
    extra = ' (call `add_global_offense`)' if node_or_range.nil?
    raise "Expected a Source::Range, got #{node_or_range.inspect}#{extra}"
  end
end

#ready

This method is for internal use only.

Called between investigations

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 300

def ready
  return self if self.class.support_multiple_source?

  self.class.new(@config, @options)
end

#relevant_file?(file) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 280

def relevant_file?(file)
  return false unless target_satisfies_all_gem_version_requirements?
  return true unless @config.clusivity_config_for_badge?(self.class.badge)

  file == RuboCop::AST::ProcessedSource::STRING_SOURCE_NAME ||
    (file_name_matches_any?(file, 'Include', true) &&
      !file_name_matches_any?(file, 'Exclude', false))
end

#reset_investigation (private)

Actually private methods

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 412

def reset_investigation
  @currently_disabled_lines = @current_offenses = @processed_source = @current_corrector = nil
end

#target_rails_version

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 268

def target_rails_version
  @config.target_rails_version
end

#target_ruby_version

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 260

def target_ruby_version
  @config.target_ruby_version
end

#use_corrector(range, corrector) ⇒ Symbol (private)

Returns:

  • (Symbol)

    offense status

[ GitHub ]

  
# File 'lib/rubocop/cop/base.rb', line 432

def use_corrector(range, corrector)
  if autocorrect?
    attempt_correction(range, corrector)
  elsif corrector && (always_autocorrect? || (contextual_autocorrect? && !LSP.enabled?))
    :uncorrected
  else
    :unsupported
  end
end