Class: RuboCop::Cop::Cop
Overview
Monkey-patch Cop for tests to provide easy access to messages and highlights.
Direct Known Subclasses
Bundler::DuplicatedGem, Bundler::GemComment, Bundler::InsecureProtocolSource, Bundler::OrderedGems, Gemspec::DuplicatedAssignment, Gemspec::OrderedDependencies, Gemspec::RequiredRubyVersion, InternalAffairs::NodeDestructuring, InternalAffairs::NodeTypePredicate, InternalAffairs::OffenseLocationKeyword, InternalAffairs::RedundantLocationArgument, InternalAffairs::RedundantMessageArgument, InternalAffairs::UselessMessageAssertion, Layout::AccessModifierIndentation, Layout::AlignArray, Layout::AlignHash, Layout::AlignParameters, 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::EmptyLineBetweenDefs, Layout::EmptyLines, Layout::EmptyLinesAroundAccessModifier, Layout::EmptyLinesAroundArguments, 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::FirstParameterIndentation, Layout::IndentArray, Layout::IndentAssignment, Layout::IndentHash, Layout::IndentHeredoc, Layout::IndentationConsistency, Layout::IndentationWidth, Layout::InitialIndentation, Layout::LeadingBlankLines, Layout::LeadingCommentSpace, Layout::MultilineArrayBraceLayout, Layout::MultilineAssignmentLayout, Layout::MultilineBlockLayout, Layout::MultilineHashBraceLayout, Layout::MultilineMethodCallBraceLayout, Layout::MultilineMethodCallIndentation, Layout::MultilineMethodDefinitionBraceLayout, Layout::MultilineOperationIndentation, Layout::RescueEnsureAlignment, Layout::SpaceAfterColon, Layout::SpaceAfterComma, Layout::SpaceAfterMethodName, Layout::SpaceAfterNot, Layout::SpaceAfterSemicolon, Layout::SpaceAroundBlockParameters, Layout::SpaceAroundEqualsInParameterDefault, Layout::SpaceAroundKeyword, 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::Tab, Layout::TrailingBlankLines, Layout::TrailingWhitespace, Lint::AmbiguousBlockAssociation, Lint::AmbiguousOperator, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BigDecimalNew, Lint::BooleanSymbol, Lint::CircularArgumentReference, Lint::Debugger, Lint::DeprecatedClassMethods, Lint::DisjunctiveAssignmentInConstructor, Lint::DuplicateCaseCondition, Lint::DuplicateMethods, Lint::DuplicatedKey, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyEnsure, Lint::EmptyExpression, Lint::EmptyInterpolation, Lint::EmptyWhen, Lint::EndInMethod, Lint::EnsureReturn, Lint::ErbNewArguments, Lint::FlipFlop, Lint::FloatOutOfRange, Lint::FormatParameterMismatch, Lint::HandleExceptions, Lint::ImplicitStringConcatenation, Lint::IneffectiveAccessModifier, Lint::InheritException, Lint::InterpolationCheck, Lint::LiteralAsCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::MissingCopEnableDirective, Lint::MultipleCompare, Lint::NestedMethodDefinition, Lint::NestedPercentLiteral, Lint::NextWithoutAccumulator, Lint::NonLocalExitFromIterator, Lint::NumberConversion, Lint::OrderedMagicComments, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RandOne, Lint::RedundantWithIndex, Lint::RedundantWithObject, Lint::RegexpAsCondition, Lint::RequireParentheses, Lint::RescueException, Lint::RescueType, Lint::ReturnInVoidContext, Lint::SafeNavigationChain, Lint::SafeNavigationConsistency, Lint::SafeNavigationWithEmpty, Lint::ScriptPermission, Lint::ShadowedArgument, Lint::ShadowedException, Lint::ShadowingOuterLocalVariable, Lint::StringConversionInInterpolation, Lint::Syntax, Lint::ToJSON, Lint::UnderscorePrefixedVariableName, Lint::UnifiedInteger, Lint::UnneededCopDisableDirective, Lint::UnneededCopEnableDirective, Lint::UnneededRequireStatement, Lint::UnneededSplatExpansion, Lint::UnreachableCode, Lint::UnusedBlockArgument, Lint::UnusedMethodArgument, Lint::UriEscapeUnescape, Lint::UriRegexp, Lint::UselessAccessModifier, Lint::UselessAssignment, Lint::UselessComparison, Lint::UselessElseWithoutRescue, Lint::UselessSetterCall, Lint::Void, Metrics::AbcSize, Metrics::BlockLength, Metrics::BlockNesting, Metrics::ClassLength, Metrics::CyclomaticComplexity, Metrics::LineLength, Metrics::MethodLength, Metrics::ModuleLength, Metrics::ParameterLists, Metrics::PerceivedComplexity, Naming::AccessorMethodName, Naming::AsciiIdentifiers, Naming::BinaryOperatorParameterName, Naming::ClassAndModuleCamelCase, Naming::ConstantName, Naming::FileName, Naming::HeredocDelimiterCase, Naming::HeredocDelimiterNaming, Naming::MemoizedInstanceVariableName, Naming::MethodName, Naming::PredicateName, Naming::UncommunicativeBlockParamName, Naming::UncommunicativeMethodParamName, Naming::VariableName, Naming::VariableNumber, Performance::Caller, Performance::CaseWhenSplat, Performance::Casecmp, Performance::ChainArrayAllocation, Performance::CompareWithBlock, Performance::Count, Performance::Detect, Performance::DoubleStartEndWith, Performance::EndWith, Performance::FixedSize, Performance::FlatMap, Performance::InefficientHashSearch, Performance::LstripRstrip, Performance::OpenStruct, Performance::RangeInclude, Performance::RedundantBlockCall, Performance::RedundantMatch, Performance::RedundantMerge, Performance::RedundantSortBy, Performance::RegexpMatch, Performance::ReverseEach, Performance::Sample, Performance::Size, Performance::StartWith, Performance::StringReplacement, Performance::TimesMap, Performance::UnfreezeString, Performance::UnneededSort, Performance::UriDefaultParser, Rails::ActionFilter, Rails::ActiveRecordAliases, Rails::ActiveSupportAliases, Rails::ApplicationJob, Rails::ApplicationRecord, Rails::AssertNot, Rails::BelongsTo, Rails::Blank, Rails::BulkChangeTable, Rails::CreateTableWithTimestamps, Rails::Date, Rails::Delegate, Rails::DelegateAllowBlank, Rails::DynamicFindBy, Rails::EnumUniqueness, Rails::EnvironmentComparison, Rails::Exit, Rails::FilePath, Rails::FindBy, Rails::FindEach, Rails::HasAndBelongsToMany, Rails::HasManyOrHasOneDependent, Rails::HttpPositionalArguments, Rails::HttpStatus, Rails::IgnoredSkipActionFilterOption, Rails::InverseOf, Rails::LexicallyScopedActionFilter, Rails::LinkToBlank, Rails::NotNullColumn, Rails::Output, Rails::OutputSafety, Rails::PluralizationGrammar, Rails::Presence, Rails::Present, Rails::ReadWriteAttribute, Rails::RedundantReceiverInWithOptions, Rails::ReflectionClassName, Rails::RefuteMethods, Rails::RelativeDateConstant, Rails::RequestReferer, Rails::ReversibleMigration, Rails::SafeNavigation, Rails::SaveBang, Rails::ScopeArgs, Rails::SkipsModelValidations, Rails::TimeZone, Rails::UniqBeforePluck, Rails::UnknownEnv, Rails::Validation, Security::Eval, Security::JSONLoad, Security::MarshalLoad, Security::Open, Security::YAMLLoad, Style::AccessModifierDeclarations, Style::Alias, Style::AndOr, Style::ArrayJoin, Style::AsciiComments, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BlockComments, Style::BlockDelimiters, Style::BracesAroundHashParameters, Style::CaseEquality, Style::CharacterLiteral, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassMethods, Style::ClassVars, Style::CollectionMethods, Style::ColonMethodCall, Style::ColonMethodDefinition, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentedKeyword, Style::ConditionalAssignment, Style::ConstantVisibility, Style::Copyright, Style::DateTime, Style::DefWithParentheses, Style::Dir, Style::Documentation, Style::DocumentationMethod, 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::For, Style::FormatString, Style::FormatStringToken, Style::FrozenStringLiteralComment, Style::GlobalVars, Style::GuardClause, Style::HashSyntax, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::IfUnlessModifierOfIfUnless, Style::IfWithSemicolon, Style::ImplicitRuntimeError, Style::InfiniteLoop, Style::InlineComment, Style::InverseMethods, Style::IpAddresses, Style::Lambda, Style::LambdaCall, Style::LineEndConcatenation, Style::MethodCallWithArgsParentheses, Style::MethodCallWithoutArgsParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MethodMissingSuper, 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::MultipleComparison, Style::MutableConstant, Style::NegatedIf, Style::NegatedWhile, Style::NestedModifier, Style::NestedParenthesizedCalls, Style::NestedTernaryOperator, Style::Next, Style::NilComparison, Style::NonNilCheck, Style::Not, Style::NumericLiteralPrefix, Style::NumericLiterals, Style::NumericPredicate, Style::OneLineConditional, Style::OptionHash, Style::OptionalArguments, Style::OrAssignment, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PreferredHashMethods, Style::Proc, Style::RaiseArgs, Style::RandomWithOffset, Style::RedundantBegin, Style::RedundantConditional, Style::RedundantException, Style::RedundantFreeze, Style::RedundantParentheses, Style::RedundantReturn, Style::RedundantSelf, Style::RegexpLiteral, Style::RescueModifier, Style::RescueStandardError, Style::ReturnNil, Style::SafeNavigation, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SignalException, Style::SingleLineBlockParams, Style::SingleLineMethods, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StderrPuts, Style::StringHashKeys, Style::StringLiterals, Style::StringLiteralsInInterpolation, Style::StringMethods, Style::StructInheritance, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::TernaryParentheses, Style::TrailingBodyOnClass, Style::TrailingBodyOnMethodDefinition, Style::TrailingBodyOnModule, Style::TrailingCommaInArguments, Style::TrailingCommaInArrayLiteral, Style::TrailingCommaInHashLiteral, Style::TrailingMethodEndStatement, Style::TrailingUnderscoreVariable, Style::TrivialAccessors, Style::UnlessElse, Style::UnneededCapitalW, Style::UnneededCondition, Style::UnneededInterpolation, Style::UnneededPercentQ, Style::UnpackFirst, Style::VariableInterpolation, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray, Style::YodaCondition, Style::ZeroLengthPredicate
Constant Summary
Constants included
from Util
Util::LITERAL_REGEX
Class Attribute Summary collapse
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from AST::Sexp
s
def_node_matcher, def_node_search, node_search, node_search_all, node_search_body, node_search_first
#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?
#ignore_node, #ignored_node?, #part_of_ignored_node?
Methods included from Util
begins_its_line?, comment_line?, double_quotes_required?, escape_string, first_part_of_call_chain, interpret_string_escapes, line_range, needs_escaping?, on_node, parentheses?, same_line?, to_string_literal, to_supported_styles, tokens, trim_string_interporation_escape_character
Methods included from PathUtil
absolute?, chdir, hidden_dir?, hidden_file_in_not_hidden_dir?, match_path?, pwd, relative_path, reset_pwd, smart_path
Constructor Details
#initialize(config = nil, options = nil) ⇒ Cop
Returns a new instance of Cop.
94
95
96
97
98
99
100
101
102
103
|
# File 'lib/rubocop/cop/cop.rb', line 94
def initialize(config = nil, options = nil)
@config = config || Config.new
@options = options || { debug: false }
@offenses = []
@corrections = []
@corrected_nodes = {}
@corrected_nodes.compare_by_identity
@processed_source = nil
end
|
Class Attribute Details
.registry ⇒ Object
Returns the value of attribute registry.
40
41
42
|
# File 'lib/rubocop/cop/cop.rb', line 40
def registry
@registry
end
|
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
34
35
36
|
# File 'lib/rubocop/cop/cop.rb', line 34
def config
@config
end
|
#corrections ⇒ Object
Returns the value of attribute corrections.
34
35
36
|
# File 'lib/rubocop/cop/cop.rb', line 34
def corrections
@corrections
end
|
#offenses ⇒ Object
Returns the value of attribute offenses.
34
35
36
|
# File 'lib/rubocop/cop/cop.rb', line 34
def offenses
@offenses
end
|
#processed_source ⇒ Object
35
36
37
|
# File 'lib/rubocop/cop/cop.rb', line 35
def processed_source
@processed_source
end
|
Class Method Details
.all ⇒ Object
43
44
45
|
# File 'lib/rubocop/cop/cop.rb', line 43
def self.all
registry.without_department(:Test).cops
end
|
.autocorrect_incompatible_with ⇒ Array<RuboCop::Cop::Cop>
List of cops that should not try to autocorrect at the same time as this cop
90
91
92
|
# File 'lib/rubocop/cop/cop.rb', line 90
def self.autocorrect_incompatible_with
[]
end
|
.badge ⇒ Object
59
60
61
|
# File 'lib/rubocop/cop/cop.rb', line 59
def self.badge
@badge ||= Badge.for(name)
end
|
.cop_name ⇒ Object
63
64
65
|
# File 'lib/rubocop/cop/cop.rb', line 63
def self.cop_name
badge.to_s
end
|
.department ⇒ Object
67
68
69
|
# File 'lib/rubocop/cop/cop.rb', line 67
def self.department
badge.department
end
|
.inherited(subclass) ⇒ Object
55
56
57
|
# File 'lib/rubocop/cop/cop.rb', line 55
def self.inherited(subclass)
registry.enlist(subclass)
end
|
.lint? ⇒ Boolean
71
72
73
|
# File 'lib/rubocop/cop/cop.rb', line 71
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.
77
78
79
80
81
82
|
# File 'lib/rubocop/cop/cop.rb', line 77
def self.match?(given_names)
return false unless given_names
given_names.include?(cop_name) ||
given_names.include?(department.to_s)
end
|
.non_rails ⇒ Object
51
52
53
|
# File 'lib/rubocop/cop/cop.rb', line 51
def self.non_rails
registry.without_department(:Rails)
end
|
.qualified_cop_name(name, origin) ⇒ Object
47
48
49
|
# File 'lib/rubocop/cop/cop.rb', line 47
def self.qualified_cop_name(name, origin)
registry.qualified_cop_name(name, origin)
end
|
Instance Method Details
#add_offense(node, location: :expression, message: nil, severity: nil) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
# File 'lib/rubocop/cop/cop.rb', line 121
def add_offense(node, location: :expression, message: nil, severity: nil)
loc = find_location(node, location)
return if duplicate_location?(loc)
severity = custom_severity || severity || default_severity
message ||= message(node)
message = annotate(message)
status = enabled_line?(loc.line) ? correct(node) : :disabled
@offenses << Offense.new(severity, loc, message, name, status)
yield if block_given? && status != :disabled
end
|
#config_to_allow_offenses ⇒ Object
160
161
162
163
|
# File 'lib/rubocop/cop/cop.rb', line 160
def config_to_allow_offenses
Formatter::DisabledConfigFormatter
.config_to_allow_offenses[cop_name] ||= {}
end
|
#config_to_allow_offenses=(hash) ⇒ Object
#cop_config ⇒ Object
109
110
111
112
113
114
|
# File 'lib/rubocop/cop/cop.rb', line 109
def cop_config
@cop_config ||= @config.for_cop(self.class.department.to_s)
.merge(@config.for_cop(self))
end
|
#cop_name ⇒ Object
Also known as:
name
182
183
184
|
# File 'lib/rubocop/cop/cop.rb', line 182
def cop_name
@cop_name ||= self.class.cop_name
end
|
#correct(node) ⇒ Object
147
148
149
150
151
152
153
154
155
156
157
158
|
# File 'lib/rubocop/cop/cop.rb', line 147
def correct(node)
return :unsupported unless support_autocorrect?
return :uncorrected unless autocorrect?
return :already_corrected if @corrected_nodes.key?(node)
@corrected_nodes[node] = true
correction = autocorrect(node)
return :uncorrected unless correction
@corrections << correction
:corrected
end
|
#duplicate_location?(location) ⇒ Boolean
143
144
145
|
# File 'lib/rubocop/cop/cop.rb', line 143
def duplicate_location?(location)
@offenses.any? { |o| o.location == location }
end
|
#excluded_file?(file) ⇒ Boolean
193
194
195
|
# File 'lib/rubocop/cop/cop.rb', line 193
def excluded_file?(file)
!relevant_file?(file)
end
|
#find_location(node, loc) ⇒ Object
rubocop:enable Metrics/CyclomaticComplexity
138
139
140
141
|
# File 'lib/rubocop/cop/cop.rb', line 138
def find_location(node, loc)
loc.is_a?(Symbol) ? node.loc.public_send(loc) : loc
end
|
#highlights ⇒ Object
90
91
92
|
# File 'lib/rubocop/rspec/cop_helper.rb', line 90
def highlights
offenses.sort.map { |o| o.location.source }
end
|
#join_force?(_force_class) ⇒ Boolean
105
106
107
|
# File 'lib/rubocop/cop/cop.rb', line 105
def join_force?(_force_class)
false
end
|
#message(_node = nil) ⇒ Object
116
117
118
|
# File 'lib/rubocop/cop/cop.rb', line 116
def message(_node = nil)
self.class::MSG
end
|
#messages ⇒ Object
86
87
88
|
# File 'lib/rubocop/rspec/cop_helper.rb', line 86
def messages
offenses.sort.map(&:message)
end
|
#parse(source, path = nil) ⇒ Object
178
179
180
|
# File 'lib/rubocop/cop/cop.rb', line 178
def parse(source, path = nil)
ProcessedSource.new(source, target_ruby_version, path)
end
|
#relevant_file?(file) ⇒ Boolean
188
189
190
191
|
# File 'lib/rubocop/cop/cop.rb', line 188
def relevant_file?(file)
file_name_matches_any?(file, 'Include', true) &&
!file_name_matches_any?(file, 'Exclude', false)
end
|
#target_rails_version ⇒ Object
174
175
176
|
# File 'lib/rubocop/cop/cop.rb', line 174
def target_rails_version
@config.target_rails_version
end
|
#target_ruby_version ⇒ Object
170
171
172
|
# File 'lib/rubocop/cop/cop.rb', line 170
def target_ruby_version
@config.target_ruby_version
end
|