Class: Locca::CollectionMerger

Inherits:
Object
  • Object
show all
Defined in:
lib/locca/collection_merger.rb

Constant Summary collapse

ACTION_ADD =
(1 << 0)
ACTION_DELETE =
(1 << 1)
ACTION_UPDATE =
(1 << 2)
ACTION_UPDATE_COMMENTS =
(1 << 3)

Instance Method Summary collapse

Instance Method Details

#merge(src_collection, dst_collection, actions = (ACTION_ADD | ACTION_DELETE)) ⇒ Object



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
# File 'lib/locca/collection_merger.rb', line 32

def merge(src_collection, dst_collection, actions = (ACTION_ADD | ACTION_DELETE))
    if not src_collection or not dst_collection
        raise ArgumentError, 'Source and Destination Collections should be set'
    end

    dst_keys = nil
    if (actions & ACTION_DELETE) != 0
        dst_keys = dst_collection.all_keys
    end

    src_collection.each do |src_item|
        dst_item = dst_collection.item_for_key(src_item.key)

        if (actions & ACTION_ADD) != 0 && !dst_item
            dst_collection.add_item(src_item.dup)
        elsif (actions & ACTION_UPDATE) != 0 && dst_item
            dst_collection.add_item(src_item.dup)
        elsif (actions & ACTION_UPDATE_COMMENTS) != 0 && dst_item
            item = CollectionItem.new(dst_item.key, dst_item.value, src_item.comment)
            dst_collection.add_item(item)
        end

        if dst_keys
            dst_keys.delete(src_item.key)
        end
    end

    if dst_keys
        dst_keys.each do |key|
            dst_collection.remove_item_for_key(key)
        end
    end
end