123456789_123456789_123456789_123456789_123456789_

Module: RuboCop::Cop::RequireLibrary

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Macros
Defined in: lib/rubocop/cop/mixin/require_library.rb

Overview

Ensure a require statement is present for a standard library determined by variable library_name

Constant Summary

Instance Method Summary

Instance Method Details

#ensure_required(corrector, node, library_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 12

def ensure_required(corrector, node, library_name)
  node = node.parent while node.parent&.parent?

  if node.parent&.begin_type?
    return if @required_libs.include?(library_name)

    remove_subsequent_requires(corrector, node, library_name)
  end

  RequireLibraryCorrector.correct(corrector, node, library_name)
end

#on_new_investigation (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 44

def on_new_investigation
  # Holds the required files at top-level
  @required_libs = Set.new
  super
end

#on_send(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 33

def on_send(node)
  return if node.parent&.parent?

  name = require_any_library?(node)
  return if name.nil?

  @required_libs.add(name)
end

#remove_subsequent_requires(corrector, node, library_name)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 24

def remove_subsequent_requires(corrector, node, library_name)
  node.right_siblings.each do |sibling|
    next unless require_library_name?(sibling, library_name)

    range = range_by_whole_lines(sibling.source_range, include_final_newline: true)
    corrector.remove(range)
  end
end

#require_any_library?(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 51

def_node_matcher :require_any_library?, <<~PATTERN
  (send {(const {nil? cbase} :Kernel) nil?} :require (str $_))
PATTERN

#require_library_name?(node, library_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/require_library.rb', line 56

def_node_matcher :require_library_name?, <<~PATTERN
  (send {(const {nil? cbase} :Kernel) nil?} :require (str %1))
PATTERN