Class: RuboCop::Cop::Base
- Inherits:
-
Object
- Object
- RuboCop::Cop::Base
- Extended by:
- NodePattern::Macros, AST::Sexp
- Includes:
- AST::Sexp, AutocorrectLogic, IgnoredNode, Util
- 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 / unparseable 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.
Direct Known Subclasses
RuboCop::Cop::Bundler::DuplicatedGem, RuboCop::Cop::Bundler::GemComment, RuboCop::Cop::Bundler::InsecureProtocolSource, Cop, Gemspec::DuplicatedAssignment, Gemspec::RequiredRubyVersion, Gemspec::RubyVersionGlobalsUsage, InternalAffairs::MethodNameEqual, InternalAffairs::NodeDestructuring, InternalAffairs::NodeTypePredicate, InternalAffairs::OffenseLocationKeyword, InternalAffairs::RedundantLocationArgument, InternalAffairs::RedundantMessageArgument, InternalAffairs::UselessMessageAssertion, Layout::BeginEndAlignment, Layout::BlockAlignment, Layout::CaseIndentation, Layout::ClassStructure, Layout::ClosingHeredocIndentation, Layout::ConditionPosition, Layout::DefEndAlignment, Layout::DotPosition, 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::FirstArrayElementLineBreak, Layout::FirstHashElementLineBreak, Layout::FirstMethodArgumentLineBreak, Layout::FirstMethodParameterLineBreak, Layout::HashAlignment, Layout::HeredocArgumentClosingParenthesis, Layout::HeredocIndentation, Layout::InitialIndentation, Layout::LeadingCommentSpace, Layout::LeadingEmptyLines, Layout::MultilineArrayBraceLayout, Layout::MultilineArrayLineBreaks, Layout::MultilineAssignmentLayout, Layout::MultilineBlockLayout, Layout::MultilineHashBraceLayout, Layout::MultilineHashKeyLineBreaks, Layout::MultilineMethodArgumentLineBreaks, Layout::MultilineMethodCallBraceLayout, Layout::MultilineMethodDefinitionBraceLayout, Layout::RescueEnsureAlignment, Layout::SpaceAfterColon, Layout::SpaceAfterComma, Layout::SpaceAfterMethodName, Layout::SpaceAfterNot, Layout::SpaceAfterSemicolon, Layout::SpaceAroundBlockParameters, Layout::SpaceAroundEqualsInParameterDefault, Layout::SpaceAroundKeyword, Layout::SpaceAroundMethodCallOperator, Layout::SpaceAroundOperators, Layout::SpaceBeforeBlockBraces, 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::AmbiguousBlockAssociation, Lint::AmbiguousOperator, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BigDecimalNew, Lint::BinaryOperatorWithIdenticalOperands, Lint::BooleanSymbol, Lint::CircularArgumentReference, Lint::ConstantDefinitionInBlock, Lint::ConstantResolution, Lint::Debugger, Lint::DeprecatedClassMethods, Lint::DeprecatedOpenSSLConstant, Lint::DisjunctiveAssignmentInConstructor, Lint::DuplicateBranch, Lint::DuplicateCaseCondition, Lint::DuplicateElsifCondition, Lint::DuplicateHashKey, Lint::DuplicateMethods, Lint::DuplicateRegexpCharacterClassElement, Lint::DuplicateRequire, Lint::DuplicateRescueException, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyBlock, Lint::EmptyClass, Lint::EmptyConditionalBody, Lint::EmptyEnsure, Lint::EmptyExpression, Lint::EmptyFile, 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::IneffectiveAccessModifier, Lint::InheritException, Lint::InterpolationCheck, Lint::LiteralAsCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::MissingCopEnableDirective, Lint::MissingSuper, Lint::MixedRegexpCaptureTypes, Lint::MultipleComparison, Lint::NestedMethodDefinition, Lint::NestedPercentLiteral, Lint::NextWithoutAccumulator, Lint::NoReturnInBeginEndBlocks, Lint::NonDeterministicRequireOrder, Lint::NonLocalExitFromIterator, Lint::NumberConversion, Lint::OrderedMagicComments, Lint::OutOfRangeRegexpRef, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RaiseException, Lint::RandOne, Lint::RedundantCopDisableDirective, Lint::RedundantCopEnableDirective, Lint::RedundantRequireStatement, Lint::RedundantSafeNavigation, Lint::RedundantSplatExpansion, Lint::RedundantStringCoercion, Lint::RedundantWithIndex, Lint::RedundantWithObject, Lint::RegexpAsCondition, Lint::RequireParentheses, 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::Syntax, Lint::ToEnumArguments, Lint::ToJSON, Lint::TopLevelReturnWithArgument, Lint::TrailingCommaInAttributeDeclaration, Lint::UnderscorePrefixedVariableName, 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::UselessSetterCall, Lint::UselessTimes, Lint::Void, Metrics::AbcSize, Metrics::BlockLength, Metrics::BlockNesting, Metrics::ClassLength, Metrics::CyclomaticComplexity, Metrics::MethodLength, Metrics::ModuleLength, Metrics::ParameterLists, Migration::DepartmentName, Naming::AccessorMethodName, Naming::AsciiIdentifiers, Naming::BinaryOperatorParameterName, Naming::BlockParameterName, Naming::ClassAndModuleCamelCase, Naming::ConstantName, Naming::FileName, Naming::HeredocDelimiterCase, Naming::HeredocDelimiterNaming, Naming::MemoizedInstanceVariableName, Naming::MethodName, Naming::MethodParameterName, Naming::PredicateName, Naming::RescuedExceptionsVariableName, Naming::VariableName, Naming::VariableNumber, Security::Eval, Security::JSONLoad, Security::MarshalLoad, Security::Open, Security::YAMLLoad, Style::AccessModifierDeclarations, Style::AccessorGrouping, Style::Alias, Style::AndOr, Style::ArgumentsForwarding, Style::ArrayCoercion, Style::ArrayJoin, Style::AsciiComments, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BisectedAttrAccessor, Style::BlockComments, Style::BlockDelimiters, Style::CaseEquality, Style::CaseLikeIf, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassEqualityComparison, Style::ClassMethods, Style::ClassMethodsDefinitions, Style::ClassVars, Style::CollectionCompact, Style::CollectionMethods, Style::ColonMethodCall, Style::ColonMethodDefinition, Style::CombinableLoops, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentedKeyword, Style::ConditionalAssignment, Style::ConstantVisibility, Style::Copyright, Style::DateTime, Style::DefWithParentheses, Style::Dir, Style::DisableCopsWithinSourceCodeDirective, Style::DocumentDynamicEvalDefinition, Style::Documentation, Style::DocumentationMethod, Style::DoubleCopDisableDirective, Style::DoubleNegation, Style::EachForSimpleLoop, Style::EachWithObject, Style::EmptyBlockParameter, Style::EmptyCaseCondition, Style::EmptyElse, Style::EmptyLambdaParameter, Style::EmptyLiteral, Style::EmptyMethod, Style::Encoding, Style::EndBlock, Style::EvalWithLocation, Style::EvenOdd, Style::ExpandPathArguments, Style::ExplicitBlockArgument, Style::ExponentialNotation, Style::FloatDivision, Style::For, Style::FormatString, Style::FormatStringToken, Style::FrozenStringLiteralComment, Style::GlobalStdStream, Style::GlobalVars, Style::GuardClause, Style::HashAsLastArrayItem, Style::HashEachMethods, Style::HashLikeCase, Style::HashTransformKeys, Style::HashTransformValues, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::IfUnlessModifierOfIfUnless, Style::IfWithSemicolon, Style::ImplicitRuntimeError, Style::InfiniteLoop, Style::InlineComment, Style::InverseMethods, Style::KeywordParametersOrder, Style::Lambda, Style::LambdaCall, Style::LineEndConcatenation, Style::MethodCallWithArgsParentheses, Style::MethodCallWithoutArgsParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MinMax, Style::MissingElse, Style::MissingRespondToMissing, Style::MixinGrouping, Style::MixinUsage, Style::ModuleFunction, Style::MultilineBlockChain, Style::MultilineIfModifier, Style::MultilineIfThen, Style::MultilineMemoization, Style::MultilineMethodSignature, Style::MultilineTernaryOperator, Style::MultilineWhenThen, Style::MultipleComparison, Style::MutableConstant, Style::NegatedIf, Style::NegatedIfElseCondition, Style::NegatedUnless, Style::NegatedWhile, Style::NestedModifier, Style::NestedParenthesizedCalls, Style::NestedTernaryOperator, Style::Next, Style::NilComparison, Style::NilLambda, Style::NonNilCheck, Style::Not, Style::NumericLiteralPrefix, Style::NumericLiterals, Style::NumericPredicate, Style::OneLineConditional, Style::OptionHash, Style::OptionalArguments, Style::OptionalBooleanParameter, Style::OrAssignment, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PreferredHashMethods, Style::Proc, Style::RaiseArgs, Style::RandomWithOffset, Style::RedundantArgument, Style::RedundantAssignment, Style::RedundantBegin, Style::RedundantCapitalW, Style::RedundantCondition, Style::RedundantConditional, Style::RedundantException, Style::RedundantFetchBlock, Style::RedundantFileExtensionInRequire, Style::RedundantFreeze, Style::RedundantInterpolation, Style::RedundantParentheses, Style::RedundantPercentQ, Style::RedundantRegexpCharacterClass, Style::RedundantRegexpEscape, Style::RedundantReturn, Style::RedundantSelf, Style::RedundantSelfAssignment, Style::RedundantSort, Style::RedundantSortBy, Style::RegexpLiteral, Style::RescueStandardError, Style::ReturnNil, Style::SafeNavigation, Style::Sample, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SignalException, Style::SingleArgumentDig, Style::SingleLineBlockParams, Style::SingleLineMethods, Style::SlicingWithRange, Style::SoleNestedConditional, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StaticClass, Style::StderrPuts, Style::StringConcatenation, Style::StringHashKeys, Style::StringMethods, Style::Strip, Style::StructInheritance, Style::SwapValues, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::TernaryParentheses, Style::TrailingBodyOnClass, Style::TrailingBodyOnMethodDefinition, Style::TrailingBodyOnModule, Style::TrailingCommaInArguments, Style::TrailingCommaInArrayLiteral, Style::TrailingCommaInBlockArgs, Style::TrailingCommaInHashLiteral, Style::TrailingMethodEndStatement, Style::TrailingUnderscoreVariable, Style::TrivialAccessors, Style::UnlessElse, Style::UnpackFirst, Style::VariableInterpolation, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray, Style::YodaCondition, Style::ZeroLengthPredicate
Defined Under Namespace
Classes: InvestigationReport
Constant Summary collapse
- RESTRICT_ON_SEND =
List of methods names to restrict calls for ‘on_send` / `on_csend`
Set[].freeze
Constants included from Util
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#processed_source ⇒ Object
readonly
Returns the value of attribute processed_source.
Class Method Summary collapse
-
.autocorrect_incompatible_with ⇒ Array<RuboCop::Cop::Cop>
List of cops that should not try to autocorrect at the same time as this cop.
-
.badge ⇒ Object
Naming.
- .callbacks_needed ⇒ Object private
- .cop_name ⇒ Object
- .department ⇒ Object
-
.documentation_url ⇒ String?
Cops (other than builtin) are encouraged to implement this.
-
.exclude_from_registry ⇒ Object
Call for abstract Cop classes.
- .inherited(subclass) ⇒ Object
-
.joining_forces ⇒ Object
Override and return the Force class(es) you need to join.
- .lint? ⇒ Boolean
-
.match?(given_names) ⇒ Boolean
Returns true if the cop name or the cop namespace matches any of the given names.
-
.support_autocorrect? ⇒ Boolean
Returns if class supports auto_correct.
-
.support_multiple_source? ⇒ Boolean
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.
Instance Method Summary collapse
-
#add_global_offense(message = nil, severity: nil) ⇒ Object
Adds an offense that has no particular location.
-
#add_offense(node_or_range, message: nil, severity: nil, &block) ⇒ Object
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.
- #callbacks_needed ⇒ Object private
- #config_to_allow_offenses ⇒ Object
- #config_to_allow_offenses=(hash) ⇒ Object
-
#cop_config ⇒ Object
Configuration Helpers.
- #cop_name ⇒ Object (also: #name)
- #excluded_file?(file) ⇒ Boolean
-
#external_dependency_checksum ⇒ Object
This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:.
-
#initialize(config = nil, options = nil) ⇒ Base
constructor
A new instance of Base.
-
#message(_range = nil) ⇒ Object
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.
-
#offenses ⇒ Object
deprecated
Deprecated.
Make potential errors with previous API more obvious
-
#on_investigation_end ⇒ Object
Called after all on_…
-
#on_new_investigation ⇒ Object
Called before all on_…
-
#on_other_file ⇒ Object
Called instead of all on_…
-
#ready ⇒ Object
private
Called between investigations.
- #relevant_file?(file) ⇒ Boolean
- #target_rails_version ⇒ Object
- #target_ruby_version ⇒ Object
Methods included from AutocorrectLogic
#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?
Methods included from IgnoredNode
#ignore_node, #ignored_node?, #part_of_ignored_node?
Methods included from Util
add_parentheses, args_begin, args_end, begins_its_line?, comment_line?, comment_lines?, double_quotes_required?, escape_string, first_part_of_call_chain, indent, interpret_string_escapes, line_range, needs_escaping?, on_node, parentheses?, same_line?, to_string_literal, to_supported_styles, trim_string_interporation_escape_character
Methods included from PathUtil
absolute?, hidden_dir?, hidden_file?, hidden_file_in_not_hidden_dir?, match_path?, maybe_hidden_file?, relative_path, smart_path
Constructor Details
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
42 43 44 |
# File 'lib/rubocop/cop/base.rb', line 42 def config @config end |
#processed_source ⇒ Object (readonly)
Returns the value of attribute processed_source.
42 43 44 |
# File 'lib/rubocop/cop/base.rb', line 42 def processed_source @processed_source end |
Class Method Details
.autocorrect_incompatible_with ⇒ Array<RuboCop::Cop::Cop>
List of cops that should not try to autocorrect at the same time as this cop
58 59 60 |
# File 'lib/rubocop/cop/base.rb', line 58 def self.autocorrect_incompatible_with [] end |
.badge ⇒ Object
Naming
168 169 170 |
# File 'lib/rubocop/cop/base.rb', line 168 def self.badge @badge ||= Badge.for(name) end |
.callbacks_needed ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
272 273 274 275 276 277 |
# File 'lib/rubocop/cop/base.rb', line 272 def self.callbacks_needed @callbacks_needed ||= public_instance_methods.select do |m| m.match?(/^on_|^after_/) && !Base.method_defined?(m) # exclude standard "callbacks" like 'on_begin_investigation' end end |
.cop_name ⇒ Object
172 173 174 |
# File 'lib/rubocop/cop/base.rb', line 172 def self.cop_name badge.to_s end |
.department ⇒ Object
176 177 178 |
# File 'lib/rubocop/cop/base.rb', line 176 def self.department badge.department end |
.documentation_url ⇒ String?
Cops (other than builtin) are encouraged to implement this
66 67 68 |
# File 'lib/rubocop/cop/base.rb', line 66 def self.documentation_url Documentation.url_for(self) if builtin? end |
.exclude_from_registry ⇒ Object
Call for abstract Cop classes
156 157 158 |
# File 'lib/rubocop/cop/base.rb', line 156 def self.exclude_from_registry Registry.global.dismiss(self) end |
.inherited(subclass) ⇒ Object
150 151 152 153 |
# File 'lib/rubocop/cop/base.rb', line 150 def self.inherited(subclass) super Registry.global.enlist(subclass) end |
.joining_forces ⇒ Object
Override and return the Force class(es) you need to join
95 |
# File 'lib/rubocop/cop/base.rb', line 95 def self.joining_forces; end |
.lint? ⇒ Boolean
180 181 182 |
# File 'lib/rubocop/cop/base.rb', line 180 def self.lint? department == :Lint end |
.match?(given_names) ⇒ Boolean
Returns true if the cop name or the cop namespace matches any of the given names.
186 187 188 189 190 191 |
# File 'lib/rubocop/cop/base.rb', line 186 def self.match?(given_names) return false unless given_names given_names.include?(cop_name) || given_names.include?(department.to_s) end |
.support_autocorrect? ⇒ Boolean
Returns if class supports auto_correct. It is recommended to extend AutoCorrector instead of overriding
162 163 164 |
# File 'lib/rubocop/cop/base.rb', line 162 def self.support_autocorrect? false end |
.support_multiple_source? ⇒ Boolean
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.
244 245 246 |
# File 'lib/rubocop/cop/base.rb', line 244 def self.support_multiple_source? false end |
Instance Method Details
#add_global_offense(message = nil, severity: nil) ⇒ Object
Adds an offense that has no particular location. No correction can be applied to global offenses
106 107 108 109 110 111 |
# File 'lib/rubocop/cop/base.rb', line 106 def add_global_offense( = nil, severity: nil) severity = find_severity(nil, severity) = (nil, ) @current_offenses << Offense.new(severity, Offense::NO_LOCATION, , name, :unsupported) end |
#add_offense(node_or_range, message: nil, severity: nil, &block) ⇒ Object
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.
117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/rubocop/cop/base.rb', line 117 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) = (range_to_pass, ) status, corrector = enabled_line?(range.line) ? correct(range, &block) : :disabled @current_offenses << Offense.new(severity, range, , name, status, corrector) end |
#callbacks_needed ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
267 268 269 |
# File 'lib/rubocop/cop/base.rb', line 267 def callbacks_needed self.class.callbacks_needed end |
#config_to_allow_offenses ⇒ Object
207 208 209 210 |
# File 'lib/rubocop/cop/base.rb', line 207 def config_to_allow_offenses Formatter::DisabledConfigFormatter .config_to_allow_offenses[cop_name] ||= {} end |
#config_to_allow_offenses=(hash) ⇒ Object
212 213 214 215 |
# File 'lib/rubocop/cop/base.rb', line 212 def config_to_allow_offenses=(hash) Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] = hash end |
#cop_config ⇒ Object
Configuration Helpers
201 202 203 204 205 |
# File 'lib/rubocop/cop/base.rb', line 201 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 ⇒ Object Also known as: name
193 194 195 |
# File 'lib/rubocop/cop/base.rb', line 193 def cop_name @cop_name ||= self.class.cop_name end |
#excluded_file?(file) ⇒ Boolean
231 232 233 |
# File 'lib/rubocop/cop/base.rb', line 231 def excluded_file?(file) !relevant_file?(file) end |
#external_dependency_checksum ⇒ Object
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.
146 147 148 |
# File 'lib/rubocop/cop/base.rb', line 146 def external_dependency_checksum nil end |
#message(_range = nil) ⇒ Object
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
100 101 102 |
# File 'lib/rubocop/cop/base.rb', line 100 def (_range = nil) self.class::MSG end |
#offenses ⇒ Object
Make potential errors with previous API more obvious
259 260 261 262 |
# File 'lib/rubocop/cop/base.rb', line 259 def offenses raise 'The offenses are not directly available; ' \ 'they are returned as the result of the investigation' end |
#on_investigation_end ⇒ Object
Called after all on_… have been called When refining this method, always call ‘super`
84 85 86 |
# File 'lib/rubocop/cop/base.rb', line 84 def on_investigation_end # Typically do nothing here end |
#on_new_investigation ⇒ Object
Called before all on_… have been called When refining this method, always call ‘super`
78 79 80 |
# File 'lib/rubocop/cop/base.rb', line 78 def on_new_investigation # Typically do nothing here end |
#on_other_file ⇒ Object
Called instead of all on_… callbacks for unrecognized files / syntax errors When refining this method, always call ‘super`
90 91 92 |
# File 'lib/rubocop/cop/base.rb', line 90 def on_other_file # Typically do nothing here end |
#ready ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Called between investigations
250 251 252 253 254 |
# File 'lib/rubocop/cop/base.rb', line 250 def ready return self if self.class.support_multiple_source? self.class.new(@config, @options) end |
#relevant_file?(file) ⇒ Boolean
225 226 227 228 229 |
# File 'lib/rubocop/cop/base.rb', line 225 def relevant_file?(file) file == RuboCop::AST::ProcessedSource::STRING_SOURCE_NAME || file_name_matches_any?(file, 'Include', true) && !file_name_matches_any?(file, 'Exclude', false) end |
#target_rails_version ⇒ Object
221 222 223 |
# File 'lib/rubocop/cop/base.rb', line 221 def target_rails_version @config.target_rails_version end |
#target_ruby_version ⇒ Object
217 218 219 |
# File 'lib/rubocop/cop/base.rb', line 217 def target_ruby_version @config.target_ruby_version end |