base.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. class Sessions::Backend::Collections::Base
  2. class << self; attr_accessor :model, :roles, :not_roles end
  3. def initialize( user, client, client_id, ttl )
  4. @user = user
  5. @client = client
  6. @client_id = client_id
  7. @ttl = ttl
  8. @last_change = nil
  9. end
  10. def load
  11. # get whole collection
  12. self.class.model.constantize.all
  13. end
  14. def client_key
  15. "collections::load::#{self.class}::#{@user.id}::#{@client_id}"
  16. end
  17. def push
  18. # check role based access
  19. if self.class.roles
  20. access = false
  21. self.class.roles.each {|role|
  22. next if !@user.role?(role)
  23. access = true
  24. break
  25. }
  26. return if !access
  27. end
  28. if self.class.not_roles
  29. access = false
  30. self.class.not_roles.each {|role|
  31. next if @user.role?(role)
  32. access = true
  33. break
  34. }
  35. return if !access
  36. end
  37. # check timeout
  38. timeout = Sessions::CacheIn.get( client_key )
  39. return if timeout
  40. # set new timeout
  41. Sessions::CacheIn.set( client_key, true, { expires_in: @ttl.seconds } )
  42. # check if update has been done
  43. last_change = self.class.model.constantize.latest_change
  44. return if last_change == @last_change
  45. @last_change = last_change
  46. # load current data
  47. items = load
  48. return if !items || items.empty?
  49. # get relations of data
  50. all = []
  51. items.each {|item|
  52. all.push item.attributes_with_associations
  53. }
  54. # collect assets
  55. assets = {}
  56. items.each {|item|
  57. assets = item.assets(assets)
  58. }
  59. if !@client
  60. return {
  61. collection: {
  62. items.first.class.to_app_model => all,
  63. },
  64. assets: assets,
  65. }
  66. end
  67. @client.log "push assets for push_collection #{items.first.class} for user #{@user.id}"
  68. @client.send(
  69. data: assets,
  70. event: [ 'loadAssets' ],
  71. )
  72. @client.log "push push_collection #{items.first.class} for user #{@user.id}"
  73. @client.send(
  74. event: 'resetCollection',
  75. data: {
  76. items.first.class.to_app_model => all,
  77. },
  78. )
  79. end
  80. def self.model_set(model)
  81. @model = model
  82. end
  83. def self.add_if_role(role)
  84. if !@roles
  85. @roles = []
  86. end
  87. @roles.push role
  88. end
  89. def self.add_if_not_role(role)
  90. if !@not_roles
  91. @not_roles = []
  92. end
  93. @not_roles.push role
  94. end
  95. end