proxy.rb 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. # This class defines a Proxy for accessing objects inside of a AssetsSet Model sub structure.
  3. #
  4. # The Zammad Assets logic works by having an Assets Hash that contains a sub structure for
  5. # each model that is relevant. Before an object gets added to the Model sub structure the
  6. # Model sub structure is checked for the presence of the object by its id. If the object is
  7. # already present it will be skipped. However, if the model is not yet present in the matching
  8. # Model sub structure the Zammad Assets will be collected and added.
  9. #
  10. # We make use of this lookup / add if not present functionality by intercepting calls to the
  11. # actual Assets Hash.
  12. #
  13. # If an object is not yet present in the Model sub structure and should be added
  14. # it will added to the lookup table of the AssetsSet first. After that the object will
  15. # be stored to the actual Assets Hash.
  16. #
  17. # The next time a lookup for an object in the Model sub structure is performed it will find the
  18. # actual object data. However, if the actual Assets Hash is send to the client and the AssetsSet
  19. # is flushed the lookup table is still present. The next time a lookup for an object in the
  20. # Model sub is performed it will NOT find the actual object data. In this case a fall back
  21. # to the lookup table will be performed which will will just return `true` to satisfy the
  22. # "is present" condition
  23. class AssetsSet < SimpleDelegator
  24. class Proxy < SimpleDelegator
  25. attr_accessor :lookup_table
  26. # This method overwrites the SimpleDelegator initializer
  27. # to be able to have the actual Assets Hash as an optional argument.
  28. def initialize(assets = {})
  29. super(assets)
  30. end
  31. # This method intercepts `assets[model_name][object_id]` calls and return the actual objects data.
  32. # If the object it not present the lookup table of the AssetsSet will be queried.
  33. # If the object was present before a previously performed `flush` it will return true and
  34. # satisfy the "is present" condition in the `assets` of the given model.
  35. # If the object is not and never was present the `assets` logic will be performed as normal.
  36. def [](id)
  37. __getobj__[id] || lookup_table[id]
  38. end
  39. # This method intercepts `assets[model_name][object_id] = object_attributes` calls.
  40. # It stores an entry in the lookup the of the AssetsSet and then performs the regular call
  41. # to store the data in the actual Assets Hash Model sub structure.
  42. def []=(id, _value)
  43. lookup_table[id] = true
  44. super
  45. end
  46. end
  47. end