class RuboCop::Cop::Lint::RedundantRequireStatement

Checks for unnecessary `require` statement.

The following features are unnecessary `require` statement because they are already loaded. e.g. Ruby 2.2:

ruby -ve 'p $LOADED_FEATURES.reject { |feature| %r|/| =~ feature }'
ruby 2.2.8p477 (2017-09-14 revision 59906) [x86_64-darwin13]
["enumerator.so", "rational.so", "complex.so", "thread.rb"]

Below are the features that each `TargetRubyVersion` targets.

* 2.0+ ... `enumerator`
* 2.1+ ... `thread`
* 2.2+ ... Add `rational` and `complex` above
* 2.5+ ... Add `pp` above
* 2.7+ ... Add `ruby2_keywords` above
* 3.1+ ... Add `fiber` above

This cop target those features.

@example

# bad
require 'unloaded_feature'
require 'thread'

# good
require 'unloaded_feature'

Constants

MSG
RESTRICT_ON_SEND
RUBY_22_LOADED_FEATURES

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/lint/redundant_require_statement.rb, line 47
def on_send(node)
  return unless redundant_require_statement?(node)

  add_offense(node) do |corrector|
    range = range_with_surrounding_space(node.loc.expression, side: :right)

    corrector.remove(range)
  end
end

Private Instance Methods

redundant_feature?(feature_name) click to toggle source

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

# File lib/rubocop/cop/lint/redundant_require_statement.rb, line 60
def redundant_feature?(feature_name)
  feature_name == 'enumerator' ||
    (target_ruby_version >= 2.1 && feature_name == 'thread') ||
    (target_ruby_version >= 2.2 && RUBY_22_LOADED_FEATURES.include?(feature_name)) ||
    (target_ruby_version >= 2.5 && feature_name == 'pp') ||
    (target_ruby_version >= 2.7 && feature_name == 'ruby2_keywords') ||
    (target_ruby_version >= 3.1 && feature_name == 'fiber')
end