Module: ActionCableNotifications::Channel::Cache

Included in:
ActionCableNotifications::Channel
Defined in:
lib/action_cable_notifications/channel_cache.rb

Instance Method Summary collapse

Instance Method Details

#update_cache(packet) ⇒ Object

Updates server side cache of client side collections XXX compute cache diff before sending to clients



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/action_cable_notifications/channel_cache.rb', line 9

def update_cache(packet)
  updated = false

  # Check if collection already exists
  new_collection = false
  if @collections[packet[:collection]].nil?
    @collections[packet[:collection]] = []
    new_collection = true
  end

  collection = @collections[packet[:collection]]

  case packet[:msg]
  when 'update_many'
    if !new_collection
      packet[:data].each do |record|
        current_record = collection.find{|c| c[:id]==record[:id]}
        if current_record
          new_record = current_record.merge(record)
          if new_record != current_record
            current_record.merge!(record)
            updated = true
          end
        end
      end
    end

  when 'upsert_many'
    if new_collection
      packet[:data].each do |record|
        collection.push record
      end
      updated = true
    else
      packet[:data].each do |record|
        current_record = collection.find{|c| c[:id]==record[:id]}
        if current_record
          new_record = current_record.merge(record)
          if new_record != current_record
            current_record.merge!(record)
            updated = true
          end
        else
          collection.push record
          updated = true
        end
      end
    end

  when 'create'
    record = collection.find{|c| c[:id]==packet[:id]}
    if !record
      @collections[packet[:collection]].push packet[:data]
      updated = true
    end

  when 'update'
    record = @collections[packet[:collection]].find{|c| c[:id]==packet[:id]}
    if record
      record.merge!(packet[:data])
      updated = true
    end

  when 'destroy'
    index = @collections[packet[:collection]].find_index{|c| c.id==packet[:id]}
    if index
      @collections[packet[:collection]].delete_at(index)
      updated = true
    end

  else
    updated = true
  end

  updated
end