upload_cache.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # A wrapper class around Store that handles temporary attachment uploads
  2. # and provides an interface for those.
  3. class UploadCache
  4. attr_reader :id
  5. # Initializes a UploadCache for a given form_id.
  6. #
  7. # @example
  8. # cache = UploadCache.new(form_id)
  9. #
  10. # @return [UploadCache]
  11. def initialize(id)
  12. # conversion to Integer is required for proper Store#o_id comparsion
  13. @id = id.to_i
  14. end
  15. # Adds a Store item with the given attributes for the form_id.
  16. #
  17. # @see Store#add
  18. #
  19. # @example
  20. # cache = UploadCache.new(form_id)
  21. # store = cache.add(
  22. # filename: file.original_filename,
  23. # data: file.read,
  24. # preferences: {
  25. # 'Content-Type' => 'application/octet-stream'
  26. # }
  27. # )
  28. #
  29. # @return [Store] the created Store item
  30. def add(args)
  31. Store.add(
  32. args.merge(
  33. object: store_object,
  34. o_id: id,
  35. )
  36. )
  37. end
  38. # Provides all Store items associated to the form_id.
  39. #
  40. # @see Store#list
  41. #
  42. # @example
  43. # attachments = UploadCache.new(form_id).attachments
  44. #
  45. # @return [Array<Store>] an enumerator of Store items
  46. def attachments
  47. Store.list(
  48. object: store_object,
  49. o_id: id,
  50. )
  51. end
  52. # Removes all Store items associated to the form_id.
  53. #
  54. # @see Store#remove
  55. #
  56. # @example
  57. # UploadCache.new(form_id).destroy
  58. #
  59. def destroy
  60. Store.remove(
  61. object: store_object,
  62. o_id: id,
  63. )
  64. end
  65. # Removes all Store items associated to the form_id.
  66. #
  67. # @see Store#remove
  68. #
  69. # @example
  70. # UploadCache.new(form_id).remove_item(store_id)
  71. #
  72. # @raise [Exceptions::UnprocessableEntity] in cases where a Store item should get deleted that is not an UploadCache item
  73. #
  74. def remove_item(store_id = nil)
  75. store = Store.find(store_id)
  76. if store.o_id != id || store.store_object_id != store_object_id
  77. raise Exceptions::UnprocessableEntity, "Attempt to delete Store item #{store_id} that is not bound to UploadCache object"
  78. end
  79. Store.remove_item(store_id)
  80. end
  81. private
  82. def store_object
  83. self.class.name
  84. end
  85. def store_object_id
  86. Store::Object.lookup(name: store_object).id
  87. end
  88. end