class RuboCop::Cop::Cop

A scaffold for concrete cops.

The Cop 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. If a cop needs to do its own processing of the AST or depends on something else, it should define the `#investigate` method and do the processing there.

@example

class CustomCop < Cop
  def investigate(processed_source)
    # Do custom processing
  end
end

Monkey-patch Cop for tests to provide easy access to messages and highlights.

Attributes

registry[R]
config[R]
corrections[R]
offenses[R]
processed_source[RW]

Public Class Methods

all() click to toggle source
# File lib/rubocop/cop/cop.rb, line 42
def self.all
  registry.without_department(:Test).cops
end
autocorrect_incompatible_with() click to toggle source

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

@return [Array<RuboCop::Cop::Cop>]

@api public

# File lib/rubocop/cop/cop.rb, line 89
def self.autocorrect_incompatible_with
  []
end
badge() click to toggle source
# File lib/rubocop/cop/cop.rb, line 58
def self.badge
  @badge ||= Badge.for(name)
end
cop_name() click to toggle source
# File lib/rubocop/cop/cop.rb, line 62
def self.cop_name
  badge.to_s
end
department() click to toggle source
# File lib/rubocop/cop/cop.rb, line 66
def self.department
  badge.department
end
inherited(subclass) click to toggle source
# File lib/rubocop/cop/cop.rb, line 54
def self.inherited(subclass)
  registry.enlist(subclass)
end
lint?() click to toggle source
# File lib/rubocop/cop/cop.rb, line 70
def self.lint?
  department == :Lint
end
match?(given_names) click to toggle source

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

# File lib/rubocop/cop/cop.rb, line 76
def self.match?(given_names)
  return false unless given_names

  given_names.include?(cop_name) ||
    given_names.include?(department.to_s)
end
new(config = nil, options = nil) click to toggle source
# File lib/rubocop/cop/cop.rb, line 93
def initialize(config = nil, options = nil)
  @config = config || Config.new
  @options = options || { debug: false }

  @offenses = []
  @corrections = []
  @processed_source = nil
end
non_rails() click to toggle source
# File lib/rubocop/cop/cop.rb, line 50
def self.non_rails
  registry.without_department(:Rails)
end
qualified_cop_name(name, origin) click to toggle source
# File lib/rubocop/cop/cop.rb, line 46
def self.qualified_cop_name(name, origin)
  registry.qualified_cop_name(name, origin)
end

Public Instance Methods

add_offense(node, *args, **kwargs, &block) click to toggle source
# File lib/rubocop/cop/cop.rb, line 117
def add_offense(node, *args, **kwargs, &block)
  if args.any?
    add_offense_deprecated(node, *args, &block)
  else
    add_offense_common(node, **kwargs, &block)
  end
end
config_to_allow_offenses() click to toggle source
# File lib/rubocop/cop/cop.rb, line 144
def config_to_allow_offenses
  Formatter::DisabledConfigFormatter
    .config_to_allow_offenses[cop_name] ||= {}
end
config_to_allow_offenses=(hash) click to toggle source
# File lib/rubocop/cop/cop.rb, line 149
def config_to_allow_offenses=(hash)
  Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] =
    hash
end
cop_config() click to toggle source
# File lib/rubocop/cop/cop.rb, line 106
def cop_config
  # Use department configuration as basis, but let individual cop
  # configuration override.
  @cop_config ||= @config.for_cop(self.class.department.to_s)
                         .merge(@config.for_cop(self))
end
cop_name() click to toggle source
# File lib/rubocop/cop/cop.rb, line 166
def cop_name
  @cop_name ||= self.class.cop_name
end
Also aliased as: name
correct(node) click to toggle source
# File lib/rubocop/cop/cop.rb, line 134
def correct(node)
  return :unsupported unless support_autocorrect?
  return :uncorrected unless autocorrect?

  correction = autocorrect(node)
  return :uncorrected unless correction
  @corrections << correction
  :corrected
end
duplicate_location?(location) click to toggle source
# File lib/rubocop/cop/cop.rb, line 130
def duplicate_location?(location)
  @offenses.any? { |o| o.location == location }
end
excluded_file?(file) click to toggle source
# File lib/rubocop/cop/cop.rb, line 177
def excluded_file?(file)
  !relevant_file?(file)
end
find_location(node, loc) click to toggle source
# File lib/rubocop/cop/cop.rb, line 125
def find_location(node, loc)
  # Location can be provided as a symbol, e.g.: `:keyword`
  loc.is_a?(Symbol) ? node.loc.public_send(loc) : loc
end
highlights() click to toggle source
# File lib/rubocop/rspec/cop_helper.rb, line 88
def highlights
  offenses.sort.map { |o| o.location.source }
end
join_force?(_force_class) click to toggle source
# File lib/rubocop/cop/cop.rb, line 102
def join_force?(_force_class)
  false
end
message(_node = nil) click to toggle source
# File lib/rubocop/cop/cop.rb, line 113
def message(_node = nil)
  self.class::MSG
end
messages() click to toggle source
# File lib/rubocop/rspec/cop_helper.rb, line 84
def messages
  offenses.sort.map(&:message)
end
name()
Alias for: cop_name
parse(source, path = nil) click to toggle source
# File lib/rubocop/cop/cop.rb, line 162
def parse(source, path = nil)
  ProcessedSource.new(source, target_ruby_version, path)
end
relevant_file?(file) click to toggle source
# File lib/rubocop/cop/cop.rb, line 172
def relevant_file?(file)
  file_name_matches_any?(file, 'Include', true) &&
    !file_name_matches_any?(file, 'Exclude', false)
end
target_rails_version() click to toggle source
# File lib/rubocop/cop/cop.rb, line 158
def target_rails_version
  @config.target_rails_version
end
target_ruby_version() click to toggle source
# File lib/rubocop/cop/cop.rb, line 154
def target_ruby_version
  @config.target_ruby_version
end

Private Instance Methods

add_offense_common(node, location: :expression, message: nil, severity: nil) { || ... } click to toggle source

rubocop:disable Metrics/CyclomaticComplexity

# File lib/rubocop/cop/cop.rb, line 247
def add_offense_common(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
add_offense_deprecated(node, loc = :expression, message = nil, severity = nil, &block) click to toggle source
# File lib/rubocop/cop/cop.rb, line 225
      def add_offense_deprecated(node, loc = :expression, message = nil,
                                 severity = nil, &block)

        caller = caller_locations(2..2).first
        path = "#{caller.path}:#{caller.lineno}"
        warn_message = <<-RUBY.strip_indent
          #{path}
          Warning: The usage of positional location, message, and severity
          parameters to Cop#add_offense is deprecated.
          Please use keyword arguments instead.

          The positional arguments version of Cop#add_offense will be removed in
          RuboCop 0.52
        RUBY

        warn(Rainbow(warn_message).red)

        add_offense_common(node, location: loc, message: message,
                                 severity: severity, &block)
      end
annotate(message) click to toggle source
# File lib/rubocop/cop/cop.rb, line 183
def annotate(message)
  RuboCop::Cop::MessageAnnotator.new(
    config, cop_config, @options
  ).annotate(message, name)
end
custom_severity() click to toggle source
# File lib/rubocop/cop/cop.rb, line 212
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() click to toggle source
# File lib/rubocop/cop/cop.rb, line 208
def default_severity
  self.class.lint? ? :warning : :convention
end
enabled_line?(line_number) click to toggle source
# File lib/rubocop/cop/cop.rb, line 203
def enabled_line?(line_number)
  return true unless @processed_source
  @processed_source.comment_config.cop_enabled_at_line?(self, line_number)
end
file_name_matches_any?(file, parameter, default_result) click to toggle source
# File lib/rubocop/cop/cop.rb, line 189
def file_name_matches_any?(file, parameter, default_result)
  patterns = cop_config[parameter]
  return default_result unless patterns
  path = nil
  patterns.any? do |pattern|
    # Try to match the absolute path, as Exclude properties are absolute.
    next true if match_path?(pattern, file)

    # Try with relative path.
    path ||= config.path_relative_to_config(file)
    match_path?(pattern, path)
  end
end