Class: ActiveShrine::Attached::One

Inherits:
Base
  • Object
show all
Defined in:
lib/active_shrine/attached/one.rb

Overview

ActiveShrineAttachedOne

Representation of a single attachment to a model.

Instance Attribute Summary

Attributes inherited from Base

#name, #record

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from ActiveShrine::Attached::Base

Instance Method Details

#attach(attachable) ⇒ Object

Attaches an attachable to the record.

If the record is persisted and unchanged, the attachment is saved to the database immediately. Otherwise, it’ll be saved to the DB when the record is next saved.

person.avatar.attach(params[:avatar]) # ActionDispatch::Http::UploadedFile object
person.avatar.attach(params[:signed_id]) # Signed reference to attachment

See https://shrinerb.com/docs/attacher#attaching for more


59
60
61
62
63
64
65
66
# File 'lib/active_shrine/attached/one.rb', line 59

def attach(attachable)
  record.public_send(:"#{name}=", attachable)
  if record.persisted? && !record.changed?
    return if !record.save
  end

  record.public_send(:"#{name}")
end

#attached?Boolean

Returns true if an attachment has been made.

class User < ApplicationRecord
  has_one_attached :avatar
end

User.new.avatar.attached? # => false

Returns:

  • (Boolean)


75
76
77
# File 'lib/active_shrine/attached/one.rb', line 75

def attached?
  attachment.present?
end

#attachmentObject

Returns the associated attachment record.

You don’t have to call this method to access the attachment’s methods as they are all available at the model level.



34
35
36
# File 'lib/active_shrine/attached/one.rb', line 34

def attachment
  change.present? ? change.attachment : record.public_send(:"#{name}_attachment")
end

#blank?Boolean

Returns true if an attachment is not attached.

class User < ApplicationRecord
  has_one_attached :avatar
end

User.new.avatar.blank? # => true

Returns:

  • (Boolean)


45
46
47
# File 'lib/active_shrine/attached/one.rb', line 45

def blank?
  !attached?
end

#detachObject

:method: detach

Deletes the attachment without purging it, leaving its blob in place.



26
# File 'lib/active_shrine/attached/one.rb', line 26

delegate :detach, to: :detach_one

#purgeObject

:method: purge

Directly purges the attachment (i.e. destroys the blob and attachment and deletes the file on the service).



14
# File 'lib/active_shrine/attached/one.rb', line 14

delegate :purge, to: :purge_one

#purge_laterObject

:method: purge_later

Purges the attachment through the queuing system.



20
# File 'lib/active_shrine/attached/one.rb', line 20

delegate :purge_later, to: :purge_one