Class: OllamaChat::Utils::JSONJSONLIO

Inherits:
Object
  • Object
show all
Defined in:
lib/ollama_chat/utils/json_jsonl_io.rb

Overview

A utility class for handling I/O operations for files in either JSON or JSONL format. The format is automatically determined by the file extension (.json or .jsonl).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = nil) ⇒ JSONJSONLIO

Initializes a new JSONJSONLIO instance.

Raises:

  • (ArgumentError)

    if the filename does not have a .json or .jsonl extension.



8
9
10
11
12
13
14
15
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 8

def initialize(filename = nil)
  @filename = Pathname.new(filename).expand_path
  @type = case @filename.extname
  when '.json'  then :json
  when '.jsonl' then :jsonl
  else raise ArgumentError, "invalid filename #{@filename.to_path.inspect}"
  end
end

Instance Attribute Details

#filenamePathname (readonly)



18
19
20
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 18

def filename
  @filename
end

Instance Method Details

#read(**opts) {|Object| ... } ⇒ Object

Reads the file and yields each element to the block.

Yields:

  • (Object)

    the parsed element.

Raises:

  • (ArgumentError)

    if no block is provided.



49
50
51
52
53
54
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 49

def read(**opts, &block)
  block or return enum_for(__method__, **opts)
  filename.open(?r) do |input|
    read_io(input:, **opts, &block)
  end
end

#read_io(input:, json_transform: Proc.id1, jsonl_transform: -> s { JSON.parse(s) }) {|Object| ... } ⇒ Object

Performs the actual read operation from the provided IO object.

Yields:

  • (Object)

    the transformed element.



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 62

def read_io(input:, json_transform: Proc.id1, jsonl_transform: -> s { JSON.parse(s) }, &block)
  block or return enum_for(__method__, input:, json_transform:, jsonl_transform:)
  case @type
  when :json
    JSON.parse(input.read).map(&json_transform).each(&block)
  when :jsonl
    input.each_line do |line|
      block.(jsonl_transform.(line))
    end
  end
end

#write(**opts) ⇒ Object

Writes a collection to the file.



23
24
25
26
27
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 23

def write(**opts)
  filename.open(?w) do |output|
    write_io(output:, **opts)
  end
end

#write_io(output:, collection:) ⇒ Object

Performs the actual write operation to the provided IO object.



33
34
35
36
37
38
39
40
41
42
# File 'lib/ollama_chat/utils/json_jsonl_io.rb', line 33

def write_io(output:, collection:)
  case @type
  when :json
    output.puts JSON.dump(collection.to_a)
  when :jsonl
    collection.each do |element|
      output.puts JSON.dump(element)
    end
  end
end