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.104 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.103 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.102 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.101 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.100 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.99 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.98 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.97 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.96 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.95 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.94 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.93 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.92 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.91 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.90 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.89 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.88 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.87 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.86 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.85 app/models/concerns/renalware/accountable.rb