Class: CachedNestedFileReader
Overview
The CachedNestedFileReader class provides functionality to read file lines with the ability to process ‘#import filename’ directives. When such a directive is encountered in a file, the corresponding ‘filename’ is read and its contents are inserted at that location. This class caches read files to avoid re-reading the same file multiple times. It allows clients to read lines with or without providing a block.
Instance Method Summary
collapse
Methods included from Exceptions
error_handler, warn_format
Constructor Details
#initialize(import_pattern: /^ *#import (.+)$/) ⇒ CachedNestedFileReader
Returns a new instance of CachedNestedFileReader.
28
29
30
31
|
# File 'lib/cached_nested_file_reader.rb', line 28
def initialize(import_pattern: /^ *#import (.+)$/)
@file_cache = {}
@import_pattern = import_pattern
end
|
Instance Method Details
#error_handler(name = '', opts = {}) ⇒ Object
33
34
35
36
37
38
|
# File 'lib/cached_nested_file_reader.rb', line 33
def error_handler(name = '', opts = {})
Exceptions.error_handler(
"CachedNestedFileReader.#{name} -- #{$!}",
opts
)
end
|
#readlines(filename, depth = 0, &block) ⇒ Object
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# File 'lib/cached_nested_file_reader.rb', line 47
def readlines(filename, depth = 0, &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 do |line|
if Regexp.new(@import_pattern) =~ line
name_strip = $~[:name].strip
included_file_path = if name_strip =~ %r{^/}
name_strip
else
File.join(directory_path, name_strip)
end
processed_lines += readlines(included_file_path, depth + 1,
&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
warn_format('readlines', "No such file -- #{filename}", { abort: true })
end
|
40
41
42
43
44
45
|
# File 'lib/cached_nested_file_reader.rb', line 40
def warn_format(name, message, opts = {})
Exceptions.warn_format(
"CachedNestedFileReader.#{name} -- #{message}",
opts
)
end
|