Sha256: 98bf63b88a644754306da5e9f9e1d130726c90926d2b8943fa03afa92eeb7765

Contents?: true

Size: 1.32 KB

Versions: 149

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

require_dependency "renalware"

module Renalware
  # Responsible for assigning a system user to the record when it is created
  # and updated.
  #
  # @example
  #
  #   clinic_visit = ClinicVisit.new(by: current_user)
  #   clinic_visit.save!
  #   clinic_visit.created_by == current_user # => true
  #   clinic_visit.updated_by == current_user # => true
  #
  module Accountable
    extend ActiveSupport::Concern

    included do
      belongs_to :created_by, class_name: "Renalware::User"
      belongs_to :updated_by, class_name: "Renalware::User"

      before_create :assign_creator
      before_update :assign_updater

      attr_accessor :by

      scope :with_created_by, -> { includes(:created_by) }
      scope :with_updated_by, -> { includes(:updated_by) }
    end

    def save_by!(user)
      self.by = user
      save!
    end

    def save_by(user)
      self.by = user
      save
    end

    def update_by(user, attrs)
      self.by = user
      update(attrs)
    end

    def first_or_create_by!(user)
      self.by = user
      first_or_create_by!
    end

    private

    def assign_creator
      self.created_by ||= by
      self.updated_by = created_by
    end

    def assign_updater
      return unless persisted?
      return if updated_by_id_changed?

      self.updated_by = by
    end
  end
end

Version data entries

149 entries across 149 versions & 1 rubygems

Version Path
renalware-core-2.0.40 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.39 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.38 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.37 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.36 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.35 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.34 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.33 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.32 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.31 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.30 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.28 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.27 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.26 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.25 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.24 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.23 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.22 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.21 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.20 app/models/concerns/renalware/accountable.rb