Sha256: 1c3e75a6c56eb88fcab693cbeadc33c0ff3dfb4ea191999ab51dc4dd7764369f

Contents?: true

Size: 1.59 KB

Versions: 6

Compression:

Stored size: 1.59 KB

Contents

module Pageflow
  class EditLock < ActiveRecord::Base
    TIME_TO_LIVE = 10.seconds

    class Error < RuntimeError
      def code
        self.class.name.split('::').last.underscore
      end
    end

    class HeldByOtherUserError < Error
      attr_reader :user

      def initialize(user)
        @user = user
      end
    end

    class HeldByOtherSessionError < Error; end
    class NotHeldError < Error; end

    belongs_to :user
    belongs_to :entry, :inverse_of => :edit_lock

    def held_by?(user)
      self.user == user
    end

    def matches?(id)
      self.id == id.to_i
    end

    def timed_out?
      Time.now > self.updated_at + TIME_TO_LIVE
    end

    def aquire(current_user, options = {})
      verify!(current_user, options)
    rescue Error
      if options[:force] || timed_out?
        entry.create_edit_lock(:user => current_user)
      else
        raise
      end
    end

    def release(current_user)
      if user == current_user
        destroy
      end
    end

    def verify!(current_user, options)
      raise HeldByOtherUserError.new(user) unless held_by?(current_user)
      raise HeldByOtherSessionError unless matches?(options[:id])
      touch
    end

    class Null
      attr_reader :entry

      def initialize(entry)
        @entry = entry
      end

      def held_by?(user)
        false
      end

      def blank?
        true
      end

      def aquire(user, options = {})
        entry.create_edit_lock!(:user => user)
      end

      def release(user)
      end

      def verify!(user, options = {})
        raise NotHeldError.new
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
pageflow-0.1.0 app/models/pageflow/edit_lock.rb
pageflow-0.0.5 app/models/pageflow/edit_lock.rb
pageflow-0.0.4 app/models/pageflow/edit_lock.rb
pageflow-0.0.3 app/models/pageflow/edit_lock.rb
pageflow-0.0.2 app/models/pageflow/edit_lock.rb
pageflow-0.0.1 app/models/pageflow/edit_lock.rb