Class: RuboCop::Cop::Kaizo::FileUtilsInclusion

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/kaizo/file_utils_inclusion.rb

Overview

Requires FileUtils to be mixed in with include (or extend) once it is used more than once in a class or module, rather than qualifying every call with the FileUtils. receiver.

Repeating the FileUtils. receiver is noise; mixing the module in once names the capability and lets the body call mkdir_p, cp, and friends directly. Use include for instance-level use and extend for class/singleton-level use. A single qualified call is left alone, and a class or module that already mixes FileUtils in is not flagged.

The class or module is reported once. Nested classes and modules are counted on their own -- one call in an outer class and one in a nested class do not add up -- and a FileUtils call in the superclass expression does not count toward the class body.

There is no autocorrection: whether to include or extend, and where the mixin belongs, is a judgment call for a human.

Examples:

# bad - the `FileUtils.` receiver is repeated
class Backup
  def run
    FileUtils.mkdir_p(dir)
    FileUtils.cp(src, dir)
  end
end

# good - mix it in once, then call unqualified
class Backup
  include FileUtils

  def run
    mkdir_p(dir)
    cp(src, dir)
  end
end

Constant Summary collapse

MSG =
"`FileUtils` is used %<count>d times in this %<scope>s; " \
"`include`/`extend` FileUtils and call its methods unqualified.".freeze

Instance Method Summary collapse

Instance Method Details

#file_utils_call?(node) ⇒ Object



46
47
48
# File 'lib/rubocop/cop/kaizo/file_utils_inclusion.rb', line 46

def_node_matcher :file_utils_call?, <<~PATTERN
  (send (const {nil? cbase} :FileUtils) ...)
PATTERN

#file_utils_mixin?(node) ⇒ Object



51
52
53
# File 'lib/rubocop/cop/kaizo/file_utils_inclusion.rb', line 51

def_node_matcher :file_utils_mixin?, <<~PATTERN
  (send nil? {:include :extend} (const {nil? cbase} :FileUtils) ...)
PATTERN

#on_class(node) ⇒ Object



55
56
57
# File 'lib/rubocop/cop/kaizo/file_utils_inclusion.rb', line 55

def on_class(node)
  check(node, "class")
end

#on_module(node) ⇒ Object



59
60
61
# File 'lib/rubocop/cop/kaizo/file_utils_inclusion.rb', line 59

def on_module(node)
  check(node, "module")
end