Sha256: 8064e663bce5c03795a797902536f08b0e7c18357a49868cf867b1a273446f30

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

module FileScanner
  # Create a scanner client
  #
  # @author c477y
  class Client
    #
    # Create a new Scanner
    #
    # @param [String] dir Directory to be processed
    # @param [Hash] options
    # @option options [Boolean] :nested Specify if nested directories should be scanned
    # @option options [String] extension Extension of filenames to be selected. Defaults to "*.mp4"
    def initialize(dir, **options)
      @nested = options[:nested]
      @extension = options[:extension].nil? ? "*.mp4" : options[:extension]
      @dir = dir
    end

    # @param [Proc] block Block of code to be executed for each file
    def each(&block)
      @block = block
      process_directory(@dir)
    end

    private

    #
    # Executes a block of code for all files in a given directory. Will scan files
    # in sub-directories if @nested is passed as true
    #
    # @param [String] dir Directory path to scan
    def process_directory(dir)
      Dir.chdir(dir) do
        # Process files in a given directory
        print "Scanning files in #{Dir.pwd}\n".colorize(:blue)

        Dir.glob(@extension).sort.each { |file| @block.call(file) }

        # Return unless we want to scan the directories inside
        # the directory `dir`
        return unless @nested

        nested_dir = Dir["*"].select { |o| File.directory?(o) }
        nested_dir.sort.each do |each|
          process_directory(each)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
file_scan-0.1.0 lib/file_scanner/client.rb