Class: Eternity::Delta

Inherits:
Object
  • Object
show all
Defined in:
lib/eternity/delta.rb

Class Method Summary collapse

Class Method Details

.merge(deltas, base_index) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/eternity/delta.rb', line 17

def merge(deltas, base_index)
  union(deltas).each_with_object({}) do |(collection, elements), hash|
    hash[collection] = {}
    elements.each do |id, changes|
      changes.each do |change|
        current_change = change
        if hash[collection][id]
          current_change = TrackFlatter.flatten [hash[collection][id], change]
          if current_change && [INSERT, UPDATE].include?(current_change['action'])
            base_data = base_index[collection].include?(id) ? base_index[collection][id].data : {}
            current_change['data'] = ConflictResolver.resolve hash[collection][id]['data'] || base_data,
                                                              change['data'],
                                                              base_data
          end
        elsif hash[collection].key?(id) && change['action'] == DELETE
          current_change = nil
        end
        hash[collection][id] = current_change
      end
      hash[collection].delete id unless hash[collection][id]
    end
    hash.delete collection if hash[collection].empty?
  end        
end

.revert(delta, index) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/eternity/delta.rb', line 42

def revert(delta, index)
  delta.each_with_object({}) do |(collection, changes), hash|
    hash[collection] = {}
    changes.each do |id, change|
      hash[collection][id] = 
        case change['action']
          when INSERT then {'action' => DELETE}
          when UPDATE then {'action' => UPDATE, 'data' => index[collection][id].data}
          when DELETE then {'action' => INSERT, 'data' => index[collection][id].data}
        end
    end
  end
end

.union(deltas) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/eternity/delta.rb', line 5

def union(deltas)
  deltas.each_with_object({}) do |delta, hash|
    delta.each do |collection, elements|
      hash[collection] ||= {}
      elements.each do |id, change|
        hash[collection][id] ||= []
        hash[collection][id] << change
      end
    end
  end
end