Class: LWS::Generic::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/lws/apps/generic.rb

Overview

The storage class

This class can be used to upload files for this app module.

Direct Known Subclasses

DigitalSignage::Storage, Resource::Storage

Class Method Summary collapse

Class Method Details

.create(file_or_io, filename, content_type = "application/octet-stream") ⇒ String?

Uploads a file (or IO object) to the storage of the app module.

The resulting storage ID can be used in model attributes that refer to storage IDs (e.g. DigitalSignage::Layout::Element#asset_storage_ids).

Parameters:

  • file_or_io (File, IO)

    the file (or IO object) to upload

  • filename (String)

    the filename to use for the uploaded file/IO object

  • content_type (String) (defaults to: "application/octet-stream")

    the content type of the uploaded file/IO object

Returns:

  • (String, nil)

    the storage ID (if successful)



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/lws/apps/generic.rb', line 211

def self.create(file_or_io, filename, content_type = "application/octet-stream")
  return nil if file_or_io.closed?

  data = file_or_io.read
  checksum = Digest::MD5.base64digest(data)
  body = { blob: { filename: filename,
                   content_type: content_type,
                   byte_size: data.length,
                   checksum: checksum } }
  res = @connection.post do |req|
    req.url "rails/active_storage/direct_uploads"
    req.headers["Accept"] = "application/json"
    req.headers["Content-Type"] = "application/json"
    req.body = body.to_json
  end

  if res.success?
    result = JSON.parse(res.body)
    res = @connection.put do |req|
      req.url result.dig("direct_upload", "url")
      result.dig("direct_upload", "headers").each do |hdr, val|
        req.headers[hdr] = val
      end
      req.body = data
    end
    if res.success?
      result["signed_id"]
    end
  else
    nil
  end
end