Repository URL to install this package:
|
Version:
0.3.5 ▾
|
# frozen_string_literal: true
require 'set'
module Datasync
# Classifies link data into the various situations
class LinkClassifier
def initialize(source_ids, target_ids, links)
@sids = Set.new source_ids
@tids = Set.new target_ids
@links = links.reject { |l| l[:source_id].nil? || l[:target_id].nil? }
assume_nothing!
end
def assume_nothing!
@assume_source_exists = false
@assume_target_exists = false
self
end
def assume_source_exists!
@assume_source_exists = true
self
end
def assume_target_exists!
@assume_target_exists = true
self
end
def link_sources
Set.new(@links.map { |l| l[:source_id] })
end
def link_targets
Set.new(@links.map { |l| l[:target_id] })
end
def source_exists?(link)
@assume_source_exists || @sids.include?(link[:source_id])
end
def target_exists?(link)
@assume_target_exists || @tids.include?(link[:target_id])
end
def classify(link)
case [source_exists?(link), target_exists?(link)]
when [true, true] then :linked
when [true, false] then :missing_target
when [false, true] then :missing_source
else :orphan
end
end
def unlinked_sources
(@sids - link_sources).map { |s| { source_id: s, target_id: nil } }
end
def unlinked_targets
(@tids - link_targets).map { |t| { source_id: nil, target_id: t } }
end
def result
classification = Hash.new { |h, k| h[k] = [] }
@links.each { |l| classification[classify(l)] << l }
classification[:unlinked_source] = unlinked_sources
classification[:unlinked_target] = unlinked_targets
classification
end
end
end