class CachedNestedFileReader
It allows clients to read lines with or without providing a block.
This class caches read files to avoid re-reading the same file multiple times.
the corresponding ‘filename’ is read and its contents are inserted at that location.
to process ‘#import filename’ directives. When such a directive is encountered in a file,
The CachedNestedFileReader class provides functionality to read file lines with the ability
#
def error_handler(name = '', opts = {})
def error_handler(name = '', opts = {}) Exceptions.error_handler( "CachedNestedFileReader.#{name} -- #{$!}", opts ) end
def initialize(import_pattern: /^ *#import (.+)$/)
def initialize(import_pattern: /^ *#import (.+)$/) @file_cache = {} @import_pattern = import_pattern end
def readlines(filename, depth = 0, context: '', import_paths: nil, &block)
def readlines(filename, depth = 0, context: '', import_paths: nil, &block) if @file_cache.key?(filename) @file_cache[filename].each(&block) if block return @file_cache[filename] end directory_path = File.dirname(filename) processed_lines = [] File.readlines(filename, chomp: true).each.with_index do |line, ind| if Regexp.new(@import_pattern) =~ line name_strip = $~[:name].strip included_file_path = if name_strip =~ %r{^/} name_strip elsif import_paths find_files(name_strip, import_paths + [directory_path])&.first else File.join(directory_path, name_strip) end processed_lines += readlines(included_file_path, depth + 1, context: "#{filename}:#{ind + 1}", import_paths: import_paths, &block) else nested_line = NestedLine.new(line, depth) processed_lines.push(nested_line) block&.call(nested_line) end end @file_cache[filename] = processed_lines rescue Errno::ENOENT # Exceptions.error_handler('readlines', { abort: true }) warn_format('readlines', "No such file -- #{filename} @@ #{context}", { abort: true }) end
def warn_format(name, message, opts = {})
def warn_format(name, message, opts = {}) Exceptions.warn_format( "CachedNestedFileReader.#{name} -- #{message}", opts ) end