class SkillsWizard
extend ActiveModel::Naming
extend ActiveModel::Translation
attr_reader :errors
attr_reader :skill, :docs_ids
def initialize(person)
@person = person
@errors = {}
@skill = nil
@docs_ids = []
end
def update_skill(s_params)
create_or_update_skill(s_params)
destroy_unused_files
end
private
def create_or_update_skill(s_params)
docs = s_params.delete(:documentations)
InterpreterSkill.find_by_id_or_create(s_params[:id]) do |skill|
s_params = price_params(s_params) if skill.approved?
skill.update(s_params)
@skill = skill
@errors.merge!(skill.errors_hash) && break if skill.errors.any?
destroy_unused_docs(docs, skill)
break unless docs.present?
update_docs(docs, skill)
end
end
def update_docs(docs, skill)
docs.each do |doc|
doc_files = doc.delete(:documentation_files)
skill.documentations.find_by_id_or_create(doc[:id]) do |documentation|
documentation.update(doc)
@errors.merge!(documentation.errors_hash)
next unless doc_files.present?
update_files(doc_files, documentation)
end
end
end
def update_files(params, documentation)
params.each do |doc_file|
begin
uploaded_file = DocumentationFile.find(doc_file)
uploaded_file.update(documentation_id: documentation.id)
rescue
next
end
end
@docs_ids = @skill.documentations.map do |d|
[d.id, d.documentation_files.last.try(:id)]
end
end
def redundant_docs_ids(docs, skill)
ids = skill.documentations.ids
if docs
docs.each do |doc|
doc_id = doc[:id].to_i
ids.delete(doc_id) if ids.include? doc_id
end
end
ids
end
def price_params(params)
params.select { |key, _| key.to_s.ends_with? '_price' }
end
def destroy_unused_docs(docs, skill)
Documentation.destroy_unused(redundant_docs_ids(docs, skill))
end
def destroy_unused_files
DocumentationFile.destroy_unused
end
end