mirror of
https://github.com/scinote-eln/scinote-web.git
synced 2024-09-20 14:45:56 +08:00
Add ProtocolIntermediateObject
This commit is contained in:
parent
aadf2eecb4
commit
6a4deb0201
|
@ -0,0 +1,57 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
module ProtocolImporters
|
||||
class ProtocolIntermediateObject
|
||||
attr_accessor :normalized_response, :user, :team
|
||||
|
||||
def initialize(normalized_json: {}, user:, team:)
|
||||
@normalized_response = normalized_json[:protocol] if normalized_json
|
||||
@user = user
|
||||
@team = team
|
||||
end
|
||||
|
||||
def import
|
||||
p = build
|
||||
p.save if p.valid?
|
||||
p
|
||||
end
|
||||
|
||||
def build
|
||||
p = build_protocol
|
||||
p.steps << build_steps
|
||||
p
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_protocol
|
||||
Protocol.new(protocol_attributes)
|
||||
end
|
||||
|
||||
def build_steps
|
||||
# TODO
|
||||
# Add:
|
||||
# - Assets
|
||||
# - Tables
|
||||
# - Checklists
|
||||
|
||||
@normalized_response[:steps].map do |s|
|
||||
Step.new(step_attributes(s))
|
||||
end
|
||||
end
|
||||
|
||||
def protocol_attributes
|
||||
defaults = { protocol_type: :in_repository_public, added_by: @user, team: @team }
|
||||
values = %i(name published_on description authors)
|
||||
p_attrs = @normalized_response.slice(*values).each_with_object({}) do |(k, v), h|
|
||||
h[k] = k == 'published_on' ? Time.at(v) : v
|
||||
end
|
||||
p_attrs.merge!(defaults)
|
||||
end
|
||||
|
||||
def step_attributes(step_json)
|
||||
defaults = { user: @user, completed: false }
|
||||
step_json.slice(:name, :position, :description).merge!(defaults)
|
||||
end
|
||||
end
|
||||
end
|
|
@ -0,0 +1,30 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
|
||||
describe ProtocolImporters::ProtocolIntermediateObject do
|
||||
subject(:pio) { described_class.new(normalized_json: normalized_result, user: user, team: team) }
|
||||
let(:invalid_pio) { described_class.new(normalized_json: normalized_result, user: nil, team: team) }
|
||||
let(:user) { create :user }
|
||||
let(:team) { create :team }
|
||||
let(:normalized_result) do
|
||||
JSON.parse(file_fixture('protocols_io/v3/normalized_single_protocol.json').read).to_h.with_indifferent_access
|
||||
end
|
||||
|
||||
describe '.build' do
|
||||
it { expect(subject.build).to be_instance_of(Protocol) }
|
||||
end
|
||||
|
||||
describe '.import' do
|
||||
context 'when have valid object' do
|
||||
it { expect { pio.import }.to change { Protocol.all.count }.by(1) }
|
||||
it { expect { pio.import }.to change { Step.all.count }.by(66) }
|
||||
it { expect(pio.import).to be_valid }
|
||||
end
|
||||
|
||||
context 'when have invalid object' do
|
||||
it { expect(invalid_pio.import).to be_invalid }
|
||||
it { expect { invalid_pio.import }.not_to(change { Protocol.all.count }) }
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue