Class: RuboCop::Cop::Cop
Overview
Monkey-patch Cop for tests to provide easy access to messages and highlights.
Direct Known Subclasses
Lint::AmbiguousOperator, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BlockAlignment, Lint::CircularArgumentReference, Lint::ConditionPosition, Lint::Debugger, Lint::DefEndAlignment, Lint::DeprecatedClassMethods, Lint::DuplicateMethods, Lint::DuplicatedKey, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyEnsure, Lint::EmptyInterpolation, Lint::EndAlignment, Lint::EndInMethod, Lint::EnsureReturn, Lint::Eval, Lint::FloatOutOfRange, Lint::FormatParameterMismatch, Lint::HandleExceptions, Lint::ImplicitStringConcatenation, Lint::IneffectiveAccessModifier, Lint::InheritException, Lint::InvalidCharacterLiteral, Lint::LiteralInCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::NestedMethodDefinition, Lint::NextWithoutAccumulator, Lint::NonLocalExitFromIterator, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RandOne, Lint::RequireParentheses, Lint::RescueException, Lint::ShadowedException, Lint::ShadowingOuterLocalVariable, Lint::StringConversionInInterpolation, Lint::UnderscorePrefixedVariableName, Lint::UnifiedInteger, Lint::UnneededDisable, Lint::UnneededSplatExpansion, Lint::UnreachableCode, Lint::UnusedBlockArgument, Lint::UnusedMethodArgument, 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, Performance::CaseWhenSplat, Performance::Casecmp, Performance::Count, Performance::Detect, Performance::DoubleStartEndWith, Performance::EndWith, Performance::FixedSize, Performance::FlatMap, Performance::HashEachMethods, Performance::LstripRstrip, Performance::RangeInclude, Performance::RedundantBlockCall, Performance::RedundantMatch, Performance::RedundantMerge, Performance::RedundantSortBy, Performance::ReverseEach, Performance::Sample, Performance::Size, Performance::SortWithBlock, Performance::StartWith, Performance::StringReplacement, Performance::TimesMap, Rails::ActionFilter, Rails::Date, Rails::Delegate, Rails::DelegateAllowBlank, Rails::DynamicFindBy, Rails::Exit, Rails::FindBy, Rails::FindEach, Rails::HasAndBelongsToMany, Rails::HttpPositionalArguments, Rails::NotNullColumn, Rails::Output, Rails::OutputSafety, Rails::PluralizationGrammar, Rails::ReadWriteAttribute, Rails::RequestReferer, Rails::SafeNavigation, Rails::SaveBang, Rails::ScopeArgs, Rails::TimeZone, Rails::UniqBeforePluck, Rails::Validation, Security::JSONLoad, Style::AccessModifierIndentation, Style::AccessorMethodName, Style::Alias, Style::AlignArray, Style::AlignHash, Style::AlignParameters, Style::AndOr, Style::ArrayJoin, Style::AsciiComments, Style::AsciiIdentifiers, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BlockComments, Style::BlockDelimiters, Style::BlockEndNewline, Style::BracesAroundHashParameters, Style::CaseEquality, Style::CaseIndentation, Style::CharacterLiteral, Style::ClassAndModuleCamelCase, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassMethods, Style::ClassVars, Style::ClosingParenthesisIndentation, Style::CollectionMethods, Style::ColonMethodCall, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentIndentation, Style::ConditionalAssignment, Style::ConstantName, Style::Copyright, Style::DefWithParentheses, Style::Documentation, Style::DocumentationMethod, Style::DotPosition, Style::DoubleNegation, Style::EachForSimpleLoop, Style::EachWithObject, Style::ElseAlignment, Style::EmptyCaseCondition, Style::EmptyElse, Style::EmptyLineBetweenDefs, Style::EmptyLines, Style::EmptyLinesAroundAccessModifier, Style::EmptyLinesAroundBlockBody, Style::EmptyLinesAroundClassBody, Style::EmptyLinesAroundMethodBody, Style::EmptyLinesAroundModuleBody, Style::EmptyLiteral, Style::Encoding, Style::EndBlock, Style::EndOfLine, Style::EvenOdd, Style::ExtraSpacing, Style::FileName, Style::FirstArrayElementLineBreak, Style::FirstHashElementLineBreak, Style::FirstMethodArgumentLineBreak, Style::FirstMethodParameterLineBreak, Style::FirstParameterIndentation, Style::FlipFlop, Style::For, Style::FormatString, Style::FrozenStringLiteralComment, Style::GlobalVars, Style::GuardClause, Style::HashSyntax, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::IfUnlessModifierOfIfUnless, Style::IfWithSemicolon, Style::ImplicitRuntimeError, Style::IndentArray, Style::IndentAssignment, Style::IndentHash, Style::IndentationConsistency, Style::IndentationWidth, Style::InfiniteLoop, Style::InitialIndentation, Style::InlineComment, Style::Lambda, Style::LambdaCall, Style::LeadingCommentSpace, Style::LineEndConcatenation, Style::MethodCallParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MethodMissing, Style::MethodName, Style::MissingElse, Style::ModuleFunction, Style::MultilineArrayBraceLayout, Style::MultilineAssignmentLayout, Style::MultilineBlockChain, Style::MultilineBlockLayout, Style::MultilineHashBraceLayout, Style::MultilineIfThen, Style::MultilineMemoization, Style::MultilineMethodCallBraceLayout, Style::MultilineMethodCallIndentation, Style::MultilineMethodDefinitionBraceLayout, Style::MultilineOperationIndentation, Style::MultilineTernaryOperator, 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::OpMethod, Style::OptionHash, Style::OptionalArguments, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PredicateName, Style::PreferredHashMethods, Style::Proc, Style::RaiseArgs, Style::RedundantBegin, Style::RedundantException, Style::RedundantFreeze, Style::RedundantParentheses, Style::RedundantReturn, Style::RedundantSelf, Style::RegexpLiteral, Style::RescueEnsureAlignment, Style::RescueModifier, Style::SafeNavigation, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SignalException, Style::SingleLineBlockParams, Style::SingleLineMethods, Style::SpaceAfterColon, Style::SpaceAfterComma, Style::SpaceAfterMethodName, Style::SpaceAfterNot, Style::SpaceAfterSemicolon, Style::SpaceAroundBlockParameters, Style::SpaceAroundEqualsInParameterDefault, Style::SpaceAroundKeyword, Style::SpaceAroundOperators, Style::SpaceBeforeBlockBraces, Style::SpaceBeforeComma, Style::SpaceBeforeComment, Style::SpaceBeforeFirstArg, Style::SpaceBeforeSemicolon, Style::SpaceInsideArrayPercentLiteral, Style::SpaceInsideBlockBraces, Style::SpaceInsideBrackets, Style::SpaceInsideHashLiteralBraces, Style::SpaceInsideParens, Style::SpaceInsidePercentLiteralDelimiters, Style::SpaceInsideRangeLiteral, Style::SpaceInsideStringInterpolation, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StringLiterals, Style::StringLiteralsInInterpolation, Style::StringMethods, Style::StructInheritance, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::Tab, Style::TernaryParentheses, Style::TrailingBlankLines, Style::TrailingCommaInArguments, Style::TrailingCommaInLiteral, Style::TrailingUnderscoreVariable, Style::TrailingWhitespace, Style::TrivialAccessors, Style::UnlessElse, Style::UnneededCapitalW, Style::UnneededInterpolation, Style::UnneededPercentQ, Style::VariableInterpolation, Style::VariableName, Style::VariableNumber, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray, Style::ZeroLengthPredicate
Constant Summary
Constants included
from Util
Util::ASGN_NODES, Util::BYTE_ORDER_MARK, Util::EQUALS_ASGN_NODES, Util::LITERAL_REGEX, Util::OPERATOR_METHODS, Util::SHORTHAND_ASGN_NODES
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from 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?, block_length, comment_line?, compatible_external_encoding_for?, directions, double_quotes_acceptable?, double_quotes_required?, effective_column, ends_its_line?, escape_string, first_part_of_call_chain, hard_to_type?, interpret_string_escapes, line_distance, line_range, move_pos, needs_escaping?, numeric_range_size, on_node, operator?, parentheses?, parenthesized_call?, preceed?, range_between, range_with_surrounding_comma, range_with_surrounding_space, same_line?, source_range, strip_quotes, stripped_source_upto, to_string_literal, to_symbol_literal, within_node?
Methods included from PathUtil
absolute?, match_path?, relative_path
Constructor Details
#initialize(config = nil, options = nil) ⇒ Cop
Returns a new instance of Cop.
127
128
129
130
131
132
133
|
# File 'lib/rubocop/cop/cop.rb', line 127
def initialize(config = nil, options = nil)
@config = config || Config.new
@options = options || { debug: false }
@offenses = []
@corrections = []
end
|
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
85
86
87
|
# File 'lib/rubocop/cop/cop.rb', line 85
def config
@config
end
|
#corrections ⇒ Object
Returns the value of attribute corrections.
85
86
87
|
# File 'lib/rubocop/cop/cop.rb', line 85
def corrections
@corrections
end
|
#offenses ⇒ Object
Returns the value of attribute offenses.
85
86
87
|
# File 'lib/rubocop/cop/cop.rb', line 85
def offenses
@offenses
end
|
#processed_source ⇒ Object
86
87
88
|
# File 'lib/rubocop/cop/cop.rb', line 86
def processed_source
@processed_source
end
|
Class Method Details
.all ⇒ Object
90
91
92
|
# File 'lib/rubocop/cop/cop.rb', line 90
def self.all
@all.without_type(:test)
end
|
.cop_name ⇒ Object
106
107
108
|
# File 'lib/rubocop/cop/cop.rb', line 106
def self.cop_name
@cop_name ||= name.split('::').last(2).join('/')
end
|
.cop_type ⇒ Object
110
111
112
|
# File 'lib/rubocop/cop/cop.rb', line 110
def self.cop_type
@cop_type ||= name.split('::')[-2].downcase.to_sym
end
|
.inherited(subclass) ⇒ Object
102
103
104
|
# File 'lib/rubocop/cop/cop.rb', line 102
def self.inherited(subclass)
@all << subclass
end
|
.lint? ⇒ Boolean
114
115
116
|
# File 'lib/rubocop/cop/cop.rb', line 114
def self.lint?
cop_type == :lint
end
|
.match?(given_names) ⇒ Boolean
Returns true if the cop name or the cop namespace matches any of the given names.
120
121
122
123
124
125
|
# File 'lib/rubocop/cop/cop.rb', line 120
def self.match?(given_names)
return false unless given_names
given_names.include?(cop_name) ||
given_names.include?(cop_type.to_s.capitalize)
end
|
.non_rails ⇒ Object
98
99
100
|
# File 'lib/rubocop/cop/cop.rb', line 98
def self.non_rails
all.without_type(:rails)
end
|
.qualified_cop_name(name, origin) ⇒ Object
94
95
96
|
# File 'lib/rubocop/cop/cop.rb', line 94
def self.qualified_cop_name(name, origin)
@all.qualified_cop_name(name, origin)
end
|
Instance Method Details
#add_offense(node, loc, message = nil, severity = nil) ⇒ Object
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
# File 'lib/rubocop/cop/cop.rb', line 166
def add_offense(node, loc, message = nil, severity = nil)
location = find_location(node, loc)
return if duplicate_location?(location)
severity = custom_severity || severity || default_severity
message ||= message(node)
message = annotate_message(message)
status = enabled_line?(location.line) ? correct(node) : :disabled
@offenses << Offense.new(severity, location, message, name, status)
yield if block_given? && status != :disabled
end
|
#config_to_allow_offenses ⇒ Object
201
202
203
204
|
# File 'lib/rubocop/cop/cop.rb', line 201
def config_to_allow_offenses
Formatter::DisabledConfigFormatter
.config_to_allow_offenses[cop_name] ||= {}
end
|
#config_to_allow_offenses=(hash) ⇒ Object
#cop_config ⇒ Object
139
140
141
|
# File 'lib/rubocop/cop/cop.rb', line 139
def cop_config
@cop_config ||= @config.for_cop(self)
end
|
#cop_name ⇒ Object
Also known as:
name
219
220
221
|
# File 'lib/rubocop/cop/cop.rb', line 219
def cop_name
@cop_name ||= self.class.cop_name
end
|
#correct(node) ⇒ Object
191
192
193
194
195
196
197
198
199
|
# File 'lib/rubocop/cop/cop.rb', line 191
def correct(node)
return :unsupported unless support_autocorrect?
return :uncorrected unless autocorrect?
correction = autocorrect(node)
return :uncorrected unless correction
@corrections << correction
:corrected
end
|
#debug? ⇒ Boolean
143
144
145
|
# File 'lib/rubocop/cop/cop.rb', line 143
def debug?
@options[:debug]
end
|
#details ⇒ Object
249
250
251
252
|
# File 'lib/rubocop/cop/cop.rb', line 249
def details
details = cop_config && cop_config['Details']
details.nil? || details.empty? ? nil : details
end
|
#display_cop_names? ⇒ Boolean
147
148
149
150
|
# File 'lib/rubocop/cop/cop.rb', line 147
def display_cop_names?
debug? || @options[:display_cop_names] ||
@config.for_all_cops['DisplayCopNames']
end
|
#display_style_guide? ⇒ Boolean
152
153
154
155
156
|
# File 'lib/rubocop/cop/cop.rb', line 152
def display_style_guide?
(style_guide_url || reference_url) &&
(@options[:display_style_guide] ||
config.for_all_cops['DisplayStyleGuide'])
end
|
#duplicate_location?(location) ⇒ Boolean
187
188
189
|
# File 'lib/rubocop/cop/cop.rb', line 187
def duplicate_location?(location)
@offenses.any? { |o| o.location == location }
end
|
#excluded_file?(file) ⇒ Boolean
230
231
232
|
# File 'lib/rubocop/cop/cop.rb', line 230
def excluded_file?(file)
!relevant_file?(file)
end
|
158
159
160
|
# File 'lib/rubocop/cop/cop.rb', line 158
def
@options[:extra_details] || config.for_all_cops['ExtraDetails']
end
|
#find_location(node, loc) ⇒ Object
182
183
184
185
|
# File 'lib/rubocop/cop/cop.rb', line 182
def find_location(node, loc)
loc.is_a?(Symbol) ? node.loc.public_send(loc) : loc
end
|
#highlights ⇒ Object
74
75
76
|
# File 'lib/rubocop/rspec/cop_helper.rb', line 74
def highlights
offenses.sort.map { |o| o.location.source }
end
|
#join_force?(_force_class) ⇒ Boolean
135
136
137
|
# File 'lib/rubocop/cop/cop.rb', line 135
def join_force?(_force_class)
false
end
|
#message(_node = nil) ⇒ Object
162
163
164
|
# File 'lib/rubocop/cop/cop.rb', line 162
def message(_node = nil)
self.class::MSG
end
|
#messages ⇒ Object
70
71
72
|
# File 'lib/rubocop/rspec/cop_helper.rb', line 70
def messages
offenses.sort.map(&:message)
end
|
#parse(source, path = nil) ⇒ Object
215
216
217
|
# File 'lib/rubocop/cop/cop.rb', line 215
def parse(source, path = nil)
ProcessedSource.new(source, target_ruby_version, path)
end
|
#reference_url ⇒ Object
244
245
246
247
|
# File 'lib/rubocop/cop/cop.rb', line 244
def reference_url
url = cop_config['Reference']
url.nil? || url.empty? ? nil : url
end
|
#relevant_file?(file) ⇒ Boolean
225
226
227
228
|
# File 'lib/rubocop/cop/cop.rb', line 225
def relevant_file?(file)
file_name_matches_any?(file, 'Include', true) &&
!file_name_matches_any?(file, 'Exclude', false)
end
|
#style_guide_url ⇒ Object
234
235
236
237
238
239
240
241
242
|
# File 'lib/rubocop/cop/cop.rb', line 234
def style_guide_url
url = cop_config['StyleGuide']
return nil if url.nil? || url.empty?
base_url = config.for_all_cops['StyleGuideBaseURL']
return url if base_url.nil? || base_url.empty?
URI.join(base_url, url).to_s
end
|
#target_ruby_version ⇒ Object
211
212
213
|
# File 'lib/rubocop/cop/cop.rb', line 211
def target_ruby_version
@config.target_ruby_version
end
|