require 'time' require 'dmao_api' require 'dmao/ingesters/errors/generic_ingester' require 'dmao/ingesters/errors/empty_attributes' module DMAO module Ingesters module Generic class Ingester ENTITY = nil ENTITY_ERROR = nil ENTITY_ERROR_MESSAGE = nil def initialize(api_url=nil, api_token=nil, institution_id=nil) DMAO::API.configure do |config| config.base_url = api_url config.api_token = api_token config.institution_id = institution_id end end def ingest raise DMAO::Ingesters::Errors::GenericIngester.new("Calling ingest on generic ingester is not allowed.") end def ingest_entity attributes = {} entity_name = self.class::ENTITY.to_s.split('::')[-1].gsub(/[A-Z]/, " \\0").strip.downcase raise DMAO::Ingesters::Errors::EmptyAttributes.new("Cannot ingest #{entity_name} without attributes.") if attributes.nil? || attributes.empty? begin entity = self.class::ENTITY.find_by_system_uuid attributes[:system_uuid] current_modified_at = Time.parse(entity.system_modified_at) new_modified_at = Time.parse(attributes[:system_modified_at]) return false if current_modified_at >= new_modified_at update_entity entity.id, attributes rescue DMAO::API::Errors::EntityNotFound add_entity attributes rescue DMAO::API::Errors::InvalidResponseLength raise self.class::ENTITY_ERROR.new("More than one #{entity_name} returned for system uuid #{attributes[:system_uuid]}.") end end def parse_unprocessable_errors errors error_messages = "" errors.each_with_index do |(k, v), index| v.each_with_index do |msg, msg_index| error_messages += "#{k} - #{msg}" error_messages += ", " unless msg_index == v.size - 1 end error_messages += ", " unless index == errors.size - 1 end raise self.class::ENTITY_ERROR.new("#{self.class::ENTITY_ERROR_MESSAGE}, #{error_messages}") end def add_entity _attributes={} raise NotImplementedError end def update_entity _entity_id, _attributes={} raise NotImplementedError end end end end end