Sha256: 712cc597509384f8f8bc036d962b1e246560315142564b1a7821f802538dc3c4

Contents?: true

Size: 1.29 KB

Versions: 22

Compression:

Stored size: 1.29 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

    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

22 entries across 22 versions & 1 rubygems

Version Path
renalware-core-2.0.0.pre.beta11 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.0.pre.beta10 app/models/concerns/renalware/accountable.rb