2017-08-14 11:56:23 +00:00
|
|
|
class Sequencer
|
|
|
|
class Unit
|
|
|
|
module Import
|
|
|
|
module Common
|
|
|
|
module Model
|
|
|
|
module Associations
|
|
|
|
class Extract < Sequencer::Unit::Base
|
|
|
|
|
|
|
|
uses :model_class, :mapped
|
|
|
|
provides :associations
|
|
|
|
|
|
|
|
def process
|
|
|
|
state.provide(:associations) do
|
|
|
|
associations.collect do |association|
|
2017-08-30 15:12:28 +00:00
|
|
|
|
|
|
|
logger.debug("Checking association '#{association}'")
|
2017-08-14 11:56:23 +00:00
|
|
|
next if !mapped.key?(association)
|
|
|
|
|
|
|
|
# remove from the mapped values if it's an association
|
|
|
|
value = mapped.delete(association)
|
2017-08-30 15:12:28 +00:00
|
|
|
logger.debug("Extracted association '#{association}' value '#{value.inspect}'")
|
2017-08-14 11:56:23 +00:00
|
|
|
|
|
|
|
# skip if we don't track them
|
|
|
|
next if tracked_associations.exclude?(association)
|
|
|
|
|
2017-08-30 15:12:28 +00:00
|
|
|
logger.debug("Using value of association '#{association}'")
|
2017-08-14 11:56:23 +00:00
|
|
|
[association, value]
|
|
|
|
end.compact.to_h
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def associations
|
|
|
|
@associations ||= begin
|
|
|
|
# loop over all reflections
|
2017-08-30 15:12:28 +00:00
|
|
|
model_class.reflect_on_all_associations.each_with_object([]) do |reflection, associations|
|
2017-08-14 11:56:23 +00:00
|
|
|
|
|
|
|
# refection name is something like groups or organization (singular/plural)
|
|
|
|
associations.push(reflection.name)
|
|
|
|
|
|
|
|
# key is something like group_id or organization_id (singular)
|
|
|
|
key = reflection.klass.name.foreign_key
|
|
|
|
|
|
|
|
# add trailing 's' to get pluralized key
|
|
|
|
reflection_name = reflection.name.to_s
|
2017-08-30 15:12:28 +00:00
|
|
|
if reflection_name.singularize != reflection_name
|
2017-08-14 11:56:23 +00:00
|
|
|
key = "#{key}s"
|
|
|
|
end
|
|
|
|
|
|
|
|
# store _id/_ids name
|
|
|
|
associations.push(key.to_sym)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def tracked_associations
|
|
|
|
# track all associations by default
|
|
|
|
associations
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|