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.1.1 app/models/concerns/renalware/accountable.rb
renalware-core-2.1.0 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.167 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.166 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.165 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.164 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.163 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.162 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.161 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.160 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.159 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.158 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.157 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.156 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.155 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.153 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.152 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.151 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.149 app/models/concerns/renalware/accountable.rb
renalware-core-2.0.148 app/models/concerns/renalware/accountable.rb