Class: ROCrate::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/ro_crate/writer.rb

Overview

A class to handle writing of RO Crates to Zip files or directories.

Instance Method Summary collapse

Constructor Details

#initialize(crate) ⇒ Writer

Initialize a new Writer for the given Crate.

Parameters:

  • crate (Crate)

    The RO Crate to be written.



8
9
10
# File 'lib/ro_crate/writer.rb', line 8

def initialize(crate)
  @crate = crate
end

Instance Method Details

#write(dir, overwrite: true) ⇒ Object

Write the crate to a directory.

Parameters:

  • dir (String)

    A path for the directory for the crate to be written to. All parent directories will be created.

  • overwrite (Boolean) (defaults to: true)

    Whether or not to overwrite existing files.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ro_crate/writer.rb', line 17

def write(dir, overwrite: true)
  FileUtils.mkdir_p(dir) # Make any parent directories
  @crate.entries.each do |path, entry|
    fullpath = ::File.join(dir, path)
    next if !overwrite && ::File.exist?(fullpath)
    next if entry.directory?
    FileUtils.mkdir_p(::File.dirname(fullpath))
    temp = Tempfile.new('ro-crate-temp')
    begin
      entry.write(temp)
      temp.close
      FileUtils.mv(temp, fullpath)
    ensure
      temp.unlink
    end
  end
end

#write_zip(destination) ⇒ Object

Write the crate to a zip file.

Parameters:

  • destination (String, ::File)

    The destination where to write the RO Crate zip.



39
40
41
42
43
44
45
46
# File 'lib/ro_crate/writer.rb', line 39

def write_zip(destination)
  Zip::File.open(destination, Zip::File::CREATE) do |zip|
    @crate.entries.each do |path, entry|
      next if entry.directory?
      zip.get_output_stream(path) { |s| entry.write(s) }
    end
  end
end