Class: Attachment

Inherits:
ApplicationRecord show all
Defined in:
app/models/attachment.rb

Constant Summary collapse

TEMPORARY_FILE_PREFIX =
'attachment'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#pathObject (readonly)

The path to the attachment contents.


14
# File 'app/models/attachment.rb', line 14

delegate :url, :path, to: :file_upload

#urlObject (readonly)

The URL to the attachment contents.


14
# File 'app/models/attachment.rb', line 14

delegate :url, :path, to: :file_upload

Class Method Details

.find_or_create_by(attributes, &block) ⇒ Attachment

Supports find_or_create_by(file: file). Similar to +find_or_initialize_by+, it will try to return an attachment with the same hash, otherwise, a new attachment is created.

Parameters:

  • attributes (Hash)

    The hash attributes with the file.

Returns:

  • (Attachment)

    The attachment which contains the file.


36
37
38
39
40
# File 'app/models/attachment.rb', line 36

def find_or_create_by(attributes, &block)
  result = find_or_initialize_by(attributes, &block)
  result.save! unless result.persisted?
  result
end

.find_or_initialize_by(attributes, &block) ⇒ Attachment

This is for supporting find_or_initialize_by(file: file). It calculates the SHA256 hash of the file and returns the attachment which has the same hash. A new attachment will be built if no record matches the hash.

Parameters:

  • attributes (Hash)

    The hash attributes with the file.

Returns:

  • (Attachment)

    The attachment which contains the file.


23
24
25
26
27
28
29
# File 'app/models/attachment.rb', line 23

def find_or_initialize_by(attributes, &block)
  file = attributes.delete(:file)
  return super unless file

  attributes[:name] = file_digest(file)
  find_by(attributes) || new(attributes.reverse_merge(file_upload: file), &block)
end

Instance Method Details

#open(opt = {}, &block) {|stream| ... } ⇒ Tempfile

Opens the attachment for reading as a stream. The options are the same as those taken by +IO.new+

This is read-only, because the attachment might not be stored on local disk.

Parameters:

  • block (Proc)

    The block to run with a reference to the stream.

  • opt (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opt):

  • :binmode (Boolean)

    If this value is a truth value, the same as 'b'.

  • :textmode (Boolean)

    If this value is a truth value, the same as 't'.

Yield Parameters:

  • stream (IO)

    The stream to read the attachment with.

Returns:

  • (Tempfile)

    When no block is provided.

  • The result of the block when a block is provided.


66
67
68
69
70
# File 'app/models/attachment.rb', line 66

def open(opt = {}, &block)
  return open_with_block(opt, block) if block

  open_without_block(opt)
end