Sha256: 855865b933b813906ba3ed38c1c5cce2a9e7973f227586535393433c2ae3e7f9

Contents?: true

Size: 1.25 KB

Versions: 33

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require_dependency "renalware/pd"
require_dependency "renalware/success"
require_dependency "renalware/failure"

module Renalware
  module PD
    class CreateRegime
      def initialize(patient:)
        @patient = patient
      end

      def call(by:, params:)
        regime = patient.pd_regimes.new(params)
        if regime.valid? && save_regime(regime, by)
          ::Renalware::Success.new(regime)
        else
          ::Renalware::Failure.new(regime)
        end
      end

      private

      attr_reader :patient

      def save_regime(new_regime, by)
        Regime.transaction do
          if update_old_regime_end_date?(current_regime, new_regime)
            current_regime.end_date ||= new_regime.start_date
          end
          current_regime.terminate(by: by).save && new_regime.save
        end
      end

      def update_old_regime_end_date?(old_regime, new_regime)
        # This odd .to_time.to_i stuff is to get around a stack overflow recursion
        # error when running rspec unit tests!
        new_regime.start_date.to_time.to_i >= old_regime.start_date.to_time.to_i
      end

      def current_regime
        @current_regime ||= patient.pd_regimes.current || NullObject.instance
      end
    end
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
renalware-core-2.0.159 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.158 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.157 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.156 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.155 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.153 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.152 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.151 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.149 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.148 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.147 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.146 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.145 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.144 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.143 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.142 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.141 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.140 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.139 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.138 app/models/renalware/pd/create_regime.rb