aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_vault/attachments.rb
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2017-07-05 15:18:50 +0200
committerDavid Heinemeier Hansson <david@loudthinking.com>2017-07-05 15:18:50 +0200
commitaaf841518866b34d769d9a951a389d1eef70d6e7 (patch)
tree81456d39a3654247196ce4cbd6bab8ab356aa0f6 /lib/active_vault/attachments.rb
parent97aa328bb1e9d43bba1bcae2c8ddbaed397770c0 (diff)
downloadrails-aaf841518866b34d769d9a951a389d1eef70d6e7.tar.gz
rails-aaf841518866b34d769d9a951a389d1eef70d6e7.tar.bz2
rails-aaf841518866b34d769d9a951a389d1eef70d6e7.zip
Add attachments
Diffstat (limited to 'lib/active_vault/attachments.rb')
-rw-r--r--lib/active_vault/attachments.rb30
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/active_vault/attachments.rb b/lib/active_vault/attachments.rb
new file mode 100644
index 0000000000..c66c142650
--- /dev/null
+++ b/lib/active_vault/attachments.rb
@@ -0,0 +1,30 @@
+require "active_vault/attachment"
+require "action_dispatch/http/upload"
+
+module ActiveVault::Attachments
+ def has_file(name)
+ define_method(name) do
+ (@active_vault_attachments ||= {})[name] ||=
+ ActiveVault::Attachment.find_by(record_gid: to_gid.to_s, name: name)&.tap { |a| a.record = self }
+ end
+
+ define_method(:"#{name}=") do |attachable|
+ case attachable
+ when ActiveVault::Blob
+ blob = attachable
+ when ActionDispatch::Http::UploadedFile
+ blob = ActiveVault::Blob.create_after_upload! \
+ io: attachable.open,
+ filename: attachable.original_filename,
+ content_type: attachable.content_type
+ when Hash
+ blob = ActiveVault::Blob.create_after_upload!(attachable)
+ when NilClass
+ blob = nil
+ end
+
+ (@active_vault_attachments ||= {})[name] = blob ?
+ ActiveVault::Attachment.create!(record_gid: to_gid.to_s, name: name, blob: blob)&.tap { |a| a.record = self } : nil
+ end
+ end
+end