Sha256: fe9599d1e8778ebea1f24736a123acda0f2b81555d5212790bc0cfad0ea26858

Contents?: true

Size: 1.03 KB

Versions: 2

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

require "active_record"
require "zeitwerk"

loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
loader.collapse("#{__dir__}/validation_errors")
loader.ignore("#{__dir__}/generators")
loader.setup

module ValidationErrors
  module Trackable
    def self.included(base)
      base.extend ClassMethods
    end

    # :nodoc:
    module ClassMethods
      def track_validation_errors
        include InstanceMethods
      end
    end

    module InstanceMethods
      def save(**options)
        super.tap do |result|
          ValidationError.track(self) unless result
        end
      end

      # Attempts to save the record just like {ActiveRecord::Base#save}[rdoc-ref:Base#save] but
      # will raise an ActiveRecord::RecordInvalid exception instead of returning +false+ if the record is not valid.
      def save!(**options)
        super
      rescue ActiveRecord::RecordInvalid
        ValidationError.track(self)
        raise
      end
    end
  end
end

ActiveRecord::Base.include ValidationErrors::Trackable

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
validation_errors-0.2.0 lib/validation_errors.rb
validation_errors-0.1.0 lib/validation_errors.rb