Sha256: f4c696ce62b98f8755a55031fc8f3e59684909338041420706a0af4ec2451e84

Contents?: true

Size: 1.21 KB

Versions: 5

Compression:

Stored size: 1.21 KB

Contents

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

    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

5 entries across 5 versions & 1 rubygems

Version Path
renalware-core-2.0.0.pre.beta9 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.0.pre.beta8 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.0.pre.beta7 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.0.pre.beta6 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.0.pre.beta5 app/models/concerns/renalware/accountable.rb