Class: JsonlReaderWriter::Reader
- Inherits:
-
Object
- Object
- JsonlReaderWriter::Reader
- Defined in:
- lib/jsonl_reader_writer/reader.rb
Overview
Reader class: Provides methods to read and process .jsonl files
Instance Method Summary collapse
-
#each ⇒ Object
each method: Opens the file, reads each line, parses it as JSON, and yields it along with its index If there’s an error parsing a line, it rescues the exception and prints an error message.
-
#filter(&block) ⇒ Object
filter method: Iterates over each line in the file and adds it to an array if it meets the condition specified in the block.
-
#initialize(file_path) ⇒ Reader
constructor
initialize method: Takes a file path as an argument, and validates that the file is a .jsonl file.
-
#map(&block) ⇒ Object
map method: Iterates over each line in the file and adds the result of the block operation to an array.
Constructor Details
#initialize(file_path) ⇒ Reader
initialize method: Takes a file path as an argument, and validates that the file is a .jsonl file
7 8 9 10 |
# File 'lib/jsonl_reader_writer/reader.rb', line 7 def initialize(file_path) @file_path = file_path validate_file_extension end |
Instance Method Details
#each ⇒ Object
each method: Opens the file, reads each line, parses it as JSON, and yields it along with its index If there’s an error parsing a line, it rescues the exception and prints an error message
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/jsonl_reader_writer/reader.rb', line 14 def each File.open(@file_path, 'r') do |f| f.each_line.with_index do |line, index| begin yield JSON.parse(line.chomp), index rescue => e puts "Error parsing line #{index + 1}: #{e.message}" end end end end |
#filter(&block) ⇒ Object
filter method: Iterates over each line in the file and adds it to an array if it meets the condition specified in the block
27 28 29 30 31 32 33 34 35 |
# File 'lib/jsonl_reader_writer/reader.rb', line 27 def filter(&block) filtered_data = [] each do |data, line_number| filtered_data << data if block.call(data) end filtered_data end |
#map(&block) ⇒ Object
map method: Iterates over each line in the file and adds the result of the block operation to an array
38 39 40 41 42 43 44 45 46 |
# File 'lib/jsonl_reader_writer/reader.rb', line 38 def map(&block) mapped_data = [] each do |data, line_number| mapped_data << block.call(data) end mapped_data end |