aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_storage/attached/one.rb
blob: d08d265992a87366dd77a36981a74964a2fd743a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ActiveStorage::Attached::One < ActiveStorage::Attached
  delegate_missing_to :attachment

  def attachment
    @attachment ||= ActiveStorage::Attachment.find_by(record_gid: record.to_gid.to_s, name: name)
  end

  def attach(attachable)
    @attachment = ActiveStorage::Attachment.create!(record_gid: record.to_gid.to_s, name: name, blob: create_blob_from(attachable))
  end

  def attached?
    attachment.present?
  end

  def purge
    if attached?
      attachment.purge
      @attachment = nil
    end
  end

  def purge_later
    if attached?
      attachment.purge_later
      @attachment = nil
    end
  end
end