Sha256: 851bdc57188a6bcba8bda6de30fb7acfd7a87bb19eb9d6a5ff8ccf091f4078e5

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 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]
      @logger = options[:logger] || $stdout
      @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
        @logger.info "Scanning files in #{Dir.pwd}".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.1 lib/file_scanner/client.rb