Sha256: 8fe60280aa5b8257629fbad25a165542a600c7b5862160cc687f62fcb939a1e3

Contents?: true

Size: 1.53 KB

Versions: 5

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

module SuperSettings
  module Storage
    # This module provides support for transactions in storage models that don't natively
    # support transactions.
    module Transaction
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        def transaction(&block)
          if Thread.current[transaction_key]
            yield Thread.current[transaction_key]
          else
            begin
              changes = []
              Thread.current[transaction_key] = changes

              yield(changes)

              if save_all(changes) != false
                changes.each do |object|
                  object.persisted = true if object.respond_to?(:persisted=)
                end
              end
            ensure
              Thread.current[transaction_key] = nil
            end
          end
        end

        def save_all(changes)
          # :nocov:
          raise NotImplementedError
          # :nocov:
        end

        private

        def transaction_key
          "#{name}.transaction"
        end
      end

      def persisted=(value)
        @persisted = Coerce.boolean(value)
      end

      def persisted?
        !!@persisted
      end

      def save!
        timestamp = Time.now
        self.updated_at ||= timestamp if respond_to?(:updated_at)
        self.created_at ||= (respond_to?(:updated_at) ? updated_at : timestamp)

        self.class.transaction do |changes|
          changes << self
        end

        true
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
super_settings-2.2.1 lib/super_settings/storage/transaction.rb
super_settings-2.2.0 lib/super_settings/storage/transaction.rb
super_settings-2.1.2 lib/super_settings/storage/transaction.rb
super_settings-2.1.1 lib/super_settings/storage/transaction.rb
super_settings-2.1.0 lib/super_settings/storage/transaction.rb