Sha256: ceb6090f99d7b01400969e6ff0d8ad2d8e35c53a906970135ff419daf52ee883

Contents?: true

Size: 1.13 KB

Versions: 5

Compression:

Stored size: 1.13 KB

Contents

require_dependency "renalware/pd"

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)
          return Success.new(regime)
        else
          return 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

5 entries across 5 versions & 1 rubygems

Version Path
renalware-core-2.0.0.pre.beta8 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.0.pre.beta7 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.0.pre.beta6 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.0.pre.beta5 app/models/renalware/pd/create_regime.rb
renalware-core-2.0.0.pre.beta4 app/models/renalware/pd/create_regime.rb