diff options
Diffstat (limited to 'lib/active_storage/attached')
-rw-r--r-- | lib/active_storage/attached/macros.rb | 23 | ||||
-rw-r--r-- | lib/active_storage/attached/many.rb | 31 | ||||
-rw-r--r-- | lib/active_storage/attached/one.rb | 29 |
3 files changed, 83 insertions, 0 deletions
diff --git a/lib/active_storage/attached/macros.rb b/lib/active_storage/attached/macros.rb new file mode 100644 index 0000000000..96493d1215 --- /dev/null +++ b/lib/active_storage/attached/macros.rb @@ -0,0 +1,23 @@ +module ActiveStorage::Attached::Macros + def has_one_attached(name, dependent: :purge_later) + define_method(name) do + instance_variable_get("@active_storage_attached_#{name}") || + instance_variable_set("@active_storage_attached_#{name}", ActiveStorage::Attached::One.new(name, self)) + end + + if dependent == :purge_later + before_destroy { public_send(name).purge_later } + end + end + + def has_many_attached(name, dependent: :purge_later) + define_method(name) do + instance_variable_get("@active_storage_attached_#{name}") || + instance_variable_set("@active_storage_attached_#{name}", ActiveStorage::Attached::Many.new(name, self)) + end + + if dependent == :purge_later + before_destroy { public_send(name).purge_later } + end + end +end diff --git a/lib/active_storage/attached/many.rb b/lib/active_storage/attached/many.rb new file mode 100644 index 0000000000..f1535dfbc6 --- /dev/null +++ b/lib/active_storage/attached/many.rb @@ -0,0 +1,31 @@ +class ActiveStorage::Attached::Many < ActiveStorage::Attached + delegate_missing_to :attachments + + def attachments + @attachments ||= ActiveStorage::Attachment.where(record_gid: record.to_gid.to_s, name: name) + end + + def attach(*attachables) + @attachments = attachments | Array(attachables).flatten.collect do |attachable| + ActiveStorage::Attachment.create!(record_gid: record.to_gid.to_s, name: name, blob: create_blob_from(attachable)) + end + end + + def attached? + attachments.any? + end + + def purge + if attached? + attachments.each(&:purge) + @attachments = nil + end + end + + def purge_later + if attached? + attachments.each(&:purge_later) + @attachments = nil + end + end +end diff --git a/lib/active_storage/attached/one.rb b/lib/active_storage/attached/one.rb new file mode 100644 index 0000000000..d08d265992 --- /dev/null +++ b/lib/active_storage/attached/one.rb @@ -0,0 +1,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 |