diff options
Diffstat (limited to 'lib/active_vault/attached')
-rw-r--r-- | lib/active_vault/attached/macros.rb | 15 | ||||
-rw-r--r-- | lib/active_vault/attached/many.rb | 22 | ||||
-rw-r--r-- | lib/active_vault/attached/one.rb | 24 |
3 files changed, 61 insertions, 0 deletions
diff --git a/lib/active_vault/attached/macros.rb b/lib/active_vault/attached/macros.rb new file mode 100644 index 0000000000..8cc84a95a9 --- /dev/null +++ b/lib/active_vault/attached/macros.rb @@ -0,0 +1,15 @@ +module ActiveVault::Attached::Macros + def has_one_attached(name) + define_method(name) do + instance_variable_get("@active_vault_attached_#{name}") || + instance_variable_set("@active_vault_attached_#{name}", ActiveVault::Attached::One.new(name, self)) + end + end + + def has_many_attached(name) + define_method(name) do + instance_variable_get("@active_vault_attached_#{name}") || + instance_variable_set("@active_vault_attached_#{name}", ActiveVault::Attached::Many.new(name, self)) + end + end +end diff --git a/lib/active_vault/attached/many.rb b/lib/active_vault/attached/many.rb new file mode 100644 index 0000000000..9f5f14ee85 --- /dev/null +++ b/lib/active_vault/attached/many.rb @@ -0,0 +1,22 @@ +class ActiveVault::Attached::Many < ActiveVault::Attached + delegate_missing_to :attachments + + def attachments + @attachments ||= ActiveVault::Attachment.where(record_gid: record.to_gid.to_s, name: name) + end + + def attach(*attachables) + @attachments = attachments + Array(attachables).collect do |attachable| + ActiveVault::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 + attachments.each(&:purge) + @attachments = nil + end +end diff --git a/lib/active_vault/attached/one.rb b/lib/active_vault/attached/one.rb new file mode 100644 index 0000000000..5566c1b971 --- /dev/null +++ b/lib/active_vault/attached/one.rb @@ -0,0 +1,24 @@ +class ActiveVault::Attached::One < ActiveVault::Attached + delegate_missing_to :attachment + + def attachment + @attachment ||= ActiveVault::Attachment.find_by(record_gid: record.to_gid.to_s, name: name) + end + + def attach(attachable) + if @attachment + # FIXME: Have options to declare dependent: :purge to clean up + end + + @attachment = ActiveVault::Attachment.create!(record_gid: record.to_gid.to_s, name: name, blob: create_blob_from(attachable)) + end + + def attached? + attachment.present? + end + + def purge + attachment.purge + @attachment = nil + end +end |