proxy.rb 2.4 KB

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