Sha256: ff179d99e2390cac9826f8b66dc18e8b090e969554bdfa307f0e98c921fc67d1

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 KB

Contents

require "tempfile"
require "delegate"

module Ddr::Models
  class WithContentFile < SimpleDelegator

    def initialize(obj, &block)
      super(obj)
      with_temp_file &block
    end

    # Yields path of tempfile containing content to block
    # @yield [String] the path to the tempfile containing content
    def with_temp_file
      filename = original_filename || content.default_file_name
      basename = [ File.basename(filename, ".*"), File.extname(filename) ]
      infile = Tempfile.open(basename, Ddr::Models.tempdir, encoding: 'ascii-8bit')
      begin
        infile.write(content.content)
        infile.close
        verify_checksum!(infile)
        yield infile.path
      ensure
        infile.close unless infile.closed?
        File.unlink(infile)
      end
    end

    def verify_checksum!(file)
      digest = Ddr::Utils.digest(File.read(file), content.checksum.algorithm)
      if digest != content.checksum.value
        raise ChecksumInvalid, "The checksum of the downloaded file does not match the stored checksum of the content."
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ddr-models-3.0.0.beta.7 lib/ddr/models/with_content_file.rb
ddr-models-3.0.0.beta.6 lib/ddr/models/with_content_file.rb
ddr-models-3.0.0.beta.4 lib/ddr/models/with_content_file.rb