Module: Shrine::InstanceMethods

Included in:
Shrine
Defined in:
lib/shrine.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#storage_keyObject (readonly)

The symbol identifier for the storage used by the uploader.


179
180
181
# File 'lib/shrine.rb', line 179

def storage_key
  @storage_key
end

Instance Method Details

#extract_metadata(io, **options) ⇒ Object

Extracts filename, size and MIME type from the file, which is later accessible through UploadedFile#metadata.


228
229
230
231
232
233
234
# File 'lib/shrine.rb', line 228

def (io, **options)
  {
    "filename"  => extract_filename(io),
    "size"      => extract_size(io),
    "mime_type" => extract_mime_type(io),
  }
end

#generate_location(io, metadata: {}, **options) ⇒ Object

Generates a unique location for the uploaded file, preserving the file extension. Can be overriden in uploaders for generating custom location.


222
223
224
# File 'lib/shrine.rb', line 222

def generate_location(io, metadata: {}, **options)
  basic_location(io, metadata: )
end

#initialize(storage_key) ⇒ Object

Accepts a storage symbol registered in `Shrine.storages`.

Shrine.new(:store)

184
185
186
187
188
# File 'lib/shrine.rb', line 184

def initialize(storage_key)
  @storage_key = storage_key.to_sym

  storage # ensure storage is registered
end

#optsObject

The class-level options hash. This should probably not be modified at the instance level.


238
239
240
# File 'lib/shrine.rb', line 238

def opts
  self.class.opts
end

#storageObject

Returns the storage object referenced by the identifier.


191
192
193
# File 'lib/shrine.rb', line 191

def storage
  self.class.find_storage(storage_key)
end

#upload(io, **options) ⇒ Object

The main method for uploading files. Takes an IO-like object and an optional context hash (used internally by Shrine::Attacher). It calls user-defined #process, and afterwards it calls #store. The `io` is closed after upload.

uploader.upload(io)
uploader.upload(io, metadata: { "foo" => "bar" })           # add metadata
uploader.upload(io, location: "path/to/file")               # specify location
uploader.upload(io, upload_options: { acl: "public-read" }) # add upload options

204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/shrine.rb', line 204

def upload(io, **options)
  _enforce_io(io)

   = (io, **options)
  location = get_location(io, **options, metadata: )

  _upload(io, **options, location: location, metadata: )

  self.class::UploadedFile.new(
    id:       location,
    storage:  storage_key,
    metadata: ,
  )
end