Sha256: 3ac9f3b9504afe7fb586ff5bb8c5f417808c21f9238034701026249ce0fba2e7

Contents?: true

Size: 1.02 KB

Versions: 2

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

require "json"
require "marc/writer"

module MARC
  class JSONLWriter < MARC::Writer
    # @param [String, IO] file A filename, or open File/IO type object, from which to read
    def initialize(file, &blk)
      if file.instance_of?(String)
        @fh = File.new(file, "w:utf-8")
      elsif file.respond_to?(:write)
        @fh = file
      else
        raise ArgumentError, "must pass in file name or handle"
      end

      if blk
        blk.call(self)
        close
      end
    end

    # Write encoded record to the handle
    # @param [MARC::Record] record
    # @return [MARC::JSONLWriter] self
    def write(record)
      @fh.puts(encode(record))
      self
    end

    # Encode the record as a marc-in-json string
    # @param [MARC::Record] record
    # @return [String] MARC-in-JSON representation of the record
    def self.encode(record)
      JSON.fast_generate(record.to_hash)
    end

    # @see MARC::JSONLWriter.encode
    def encode(rec)
      self.class.encode(rec)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
marc-1.3.0 lib/marc/jsonl_writer.rb
marc-1.2.0 lib/marc/jsonl_writer.rb