Sha256: 4401d40bd744576e4a79fd04eb80b31723fa4cff0e8b751e9588c2c06609fa3a

Contents?: true

Size: 805 Bytes

Versions: 38

Compression:

Stored size: 805 Bytes

Contents

# frozen_string_literal: true

module Alchemy
  class PageMutex < BaseRecord
    class LockFailed < StandardError; end

    MAX_AGE = 300 # seconds

    belongs_to :page, class_name: "Alchemy::Page", optional: true

    scope :expired, -> { where(arel_table[:created_at].lteq(MAX_AGE.seconds.ago)) }

    def self.with_lock!(page)
      raise ArgumentError, "A page is necessary to lock it" if page.nil?

      # remove old expired page if it wasn't deleted before
      expired.where(page: page).delete_all

      begin
        page_mutex = create!(page: page)
      rescue ActiveRecord::RecordNotUnique
        error = LockFailed.new("Can't lock page #{page.id} twice!")
        logger.error error.inspect
        raise error
      end
      yield
    ensure
      page_mutex&.destroy
    end
  end
end

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
alchemy_cms-7.3.4 app/models/alchemy/page_mutex.rb
alchemy_cms-7.3.3 app/models/alchemy/page_mutex.rb
alchemy_cms-7.3.2 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.7 app/models/alchemy/page_mutex.rb
alchemy_cms-7.3.1 app/models/alchemy/page_mutex.rb
alchemy_cms-7.3.0 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.6 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.5 app/models/alchemy/page_mutex.rb
alchemy_cms-7.1.12 app/models/alchemy/page_mutex.rb
alchemy_cms-7.0.15 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.4 app/models/alchemy/page_mutex.rb
alchemy_cms-7.1.11 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.3 app/models/alchemy/page_mutex.rb
alchemy_cms-7.1.10 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.2 app/models/alchemy/page_mutex.rb
alchemy_cms-7.1.9 app/models/alchemy/page_mutex.rb
alchemy_cms-7.0.14 app/models/alchemy/page_mutex.rb
alchemy_cms-7.2.1 app/models/alchemy/page_mutex.rb
alchemy_cms-7.0.13 app/models/alchemy/page_mutex.rb
alchemy_cms-7.1.8 app/models/alchemy/page_mutex.rb