Class: GRApiManager::FilePayload

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

Overview


FilePayload — wraps an uploaded file (multipart or raw) with a clean API.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tempfile:, filename:, content_type:) ⇒ FilePayload

Returns a new instance of FilePayload.



75
76
77
78
79
80
# File 'lib/gr_api_manager.rb', line 75

def initialize(tempfile:, filename:, content_type:)
  @tempfile     = tempfile
  @filename     = filename.to_s
  @content_type = content_type.to_s
  @size         = tempfile.respond_to?(:size) ? tempfile.size : tempfile.length
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



73
74
75
# File 'lib/gr_api_manager.rb', line 73

def content_type
  @content_type
end

#filenameObject (readonly)

Returns the value of attribute filename.



73
74
75
# File 'lib/gr_api_manager.rb', line 73

def filename
  @filename
end

#sizeObject (readonly)

Returns the value of attribute size.



73
74
75
# File 'lib/gr_api_manager.rb', line 73

def size
  @size
end

#tempfileObject (readonly)

Returns the value of attribute tempfile.



73
74
75
# File 'lib/gr_api_manager.rb', line 73

def tempfile
  @tempfile
end

Instance Method Details

#extensionObject

Convenience: the file extension derived from the original filename.



109
110
111
# File 'lib/gr_api_manager.rb', line 109

def extension
  File.extname(@filename).downcase
end

#inspectObject



123
124
125
126
# File 'lib/gr_api_manager.rb', line 123

def inspect
  "#<GRApiManager::FilePayload filename=#{@filename.inspect} " \
    "content_type=#{@content_type.inspect} size=#{@size}>"
end

#readObject

Returns the raw binary content of the file as a String (encoding: BINARY).



83
84
85
86
87
88
89
90
# File 'lib/gr_api_manager.rb', line 83

def read
  if @tempfile.respond_to?(:read)
    @tempfile.rewind
    @tempfile.read
  else
    @tempfile.to_s.force_encoding(Encoding::BINARY)
  end
end

#save_to(dest_path) ⇒ Object

Saves the uploaded content to dest_path on disk. Returns dest_path.



103
104
105
106
# File 'lib/gr_api_manager.rb', line 103

def save_to(dest_path)
  File.open(dest_path, 'wb') { |f| f.write(read) }
  dest_path
end

#to_base64Object

Returns the file content encoded as a Base64 string (no newlines).



93
94
95
# File 'lib/gr_api_manager.rb', line 93

def to_base64
  Base64.strict_encode64(read)
end

#to_hObject

Human-friendly summary — safe to include in JSON responses.



114
115
116
117
118
119
120
121
# File 'lib/gr_api_manager.rb', line 114

def to_h
  {
    filename:     @filename,
    content_type: @content_type,
    size:         @size,
    extension:    extension
  }
end

#to_hexObject

Returns the file content encoded as a lowercase hexadecimal string.



98
99
100
# File 'lib/gr_api_manager.rb', line 98

def to_hex
  read.unpack1('H*')
end