Class: Trailblazer::Operation::UploadedFile

Inherits:
Object
  • Object
show all
Defined in:
lib/trailblazer/operation/uploaded_file.rb

Overview

TODO: document: to_hash from_hash initialize/tmp_dir

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uploaded, options = {}) ⇒ UploadedFile

Returns a new instance of UploadedFile.



11
12
13
14
15
# File 'lib/trailblazer/operation/uploaded_file.rb', line 11

def initialize(uploaded, options={})
  @uploaded = uploaded
  @options  = options
  @tmp_dir  = options[:tmp_dir]
end

Class Method Details

.from_hash(hash) ⇒ Object

Returns a ActionDispatch::Http::UploadedFile as if the upload was in the same request.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/trailblazer/operation/uploaded_file.rb', line 32

def self.from_hash(hash)
  suffix = File.extname(hash[:filename])

  # we need to create a Tempfile to make Http::UploadedFile work.
  tmp  = Tempfile.new(["bla", suffix]) # always force file suffix to avoid problems with imagemagick etc.
  file = File.open(hash[:tempfile_path])# doesn't close automatically :( # fixme: introduce strategy (Tempfile:=>slow, File:=> hopefully less memory footprint)
  tmp.write(file.read) # DISCUSS: We need Tempfile.new(<File>) to avoid this slow and memory-consuming mechanics.

  file.close # TODO: can we test that?
  File.unlink(file)

  ActionDispatch::Http::UploadedFile.new(hash.merge(tempfile: tmp))
end

Instance Method Details

#to_hashObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/trailblazer/operation/uploaded_file.rb', line 17

def to_hash
  path = persist!

  hash = {
    filename: @uploaded.original_filename,
    type: @uploaded.content_type,
    tempfile_path: path
  }

  cleanup!

  hash
end