Sha256: 0c0fbf032d224d02223df5e87916625a7cdc73c882f08271fc2bc3912b26ba6b

Contents?: true

Size: 1.03 KB

Versions: 4

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

module Spandx
  module Rubygems
    class DataFile
      attr_reader :path

      def initialize(path, default: {})
        @path = path
        @default = default
      end

      def data
        @data ||= read(default: @default)
      end

      def size
        File.size(path)
      end

      def batch(size:)
        Zlib::GzipWriter.open(path) do |io|
          packer = MessagePack::Packer.new(io)
          packer.write_map_header(size)
          yield packer
          packer.flush
        end
      end

      def save!
        write(data)
      end

      private

      def read(default: nil)
        return default unless File.exist?(path)
        return default if File.empty?(path)

        MessagePack.unpack(Zlib::GzipReader.open(path, &:read))
      end

      def write(data)
        FileUtils.mkdir_p(File.dirname(path))
        Zlib::GzipWriter.open(path) do |io|
          packer = MessagePack::Packer.new(io)
          packer.write(data)
          packer.flush
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
spandx-rubygems-0.1.3 lib/spandx/rubygems/data_file.rb
spandx-rubygems-0.1.2 lib/spandx/rubygems/data_file.rb
spandx-rubygems-0.1.1 lib/spandx/rubygems/data_file.rb
spandx-rubygems-0.1.0 lib/spandx/rubygems/data_file.rb