has_attachments.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::HasAttachments
  3. extend ActiveSupport::Concern
  4. included do
  5. after_create :attachments_buffer_check
  6. after_update :attachments_buffer_check
  7. end
  8. =begin
  9. get list of attachments of this object
  10. item = Model.find(123)
  11. list = item.attachments
  12. returns
  13. # array with Store model objects
  14. =end
  15. def attachments
  16. Store.list(object: self.class.to_s, o_id: id)
  17. end
  18. =begin
  19. store attachments for this object
  20. item = Model.find(123)
  21. item.attachments = [ Store-Object1, Store-Object2 ]
  22. =end
  23. def attachments=(attachments)
  24. self.attachments_buffer = attachments
  25. # update if object already exists
  26. return if !(id && id.nonzero?)
  27. attachments_buffer_check
  28. end
  29. private
  30. def attachments_buffer
  31. @attachments_buffer_data
  32. end
  33. def attachments_buffer=(attachments)
  34. @attachments_buffer_data = attachments
  35. end
  36. def attachments_buffer_check
  37. # do nothing if no attachment exists
  38. return 1 if attachments_buffer.nil?
  39. # store attachments
  40. article_store = []
  41. attachments_buffer.each do |attachment|
  42. article_store.push Store.add(
  43. object: self.class.to_s,
  44. o_id: id,
  45. data: attachment.content,
  46. filename: attachment.filename,
  47. preferences: attachment.preferences,
  48. created_by_id: created_by_id,
  49. )
  50. end
  51. attachments_buffer = nil
  52. end
  53. end