Sha256: d8866bbdb13d2a6352aef76126c9e2cd2f170067f5f22ae817a0fc54c4fc1deb

Contents?: true

Size: 1.23 KB

Versions: 21

Compression:

Stored size: 1.23 KB

Contents

module Ruco
  class History
    attr_accessor :timeout

    def initialize(options)
      @options = options
      @stack = [@options.delete(:state)]
      @timeout = options.delete(:timeout) || 0
      timeout!
      @position = 0
    end

    def state
      @stack[@position]
    end

    def add(state)
      return unless tracked_field_changes?(state)
      remove_undone_states
      if merge_timeout?
        @position += 1
        @last_merge = Time.now.to_f
      end
      @stack[@position] = state
      limit_stack
    end

    def undo
      timeout!
      @position = [@position - 1, 0].max
    end

    def redo
      timeout!
      @position = [@position + 1, @stack.size - 1].min
    end

    private

    def remove_undone_states
      @stack.slice!(@position + 1, 9999999)
    end

    def tracked_field_changes?(data)
      @options[:track].any? do |field|
        state[field] != data[field]
      end
    end

    def limit_stack
      to_remove = @stack.size - @options[:entries]
      return if to_remove < 1
      @stack.slice!(0, to_remove)
      @position -= to_remove
    end

    def timeout!
      @last_merge = Time.now.to_f - @timeout
    end

    def merge_timeout?
      (Time.now.to_f - @last_merge) > @timeout
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
ruco-0.0.55 lib/ruco/history.rb
ruco-0.0.54 lib/ruco/history.rb
ruco-0.0.53 lib/ruco/history.rb
ruco-0.0.52 lib/ruco/history.rb
ruco-0.0.51 lib/ruco/history.rb
ruco-0.0.50 lib/ruco/history.rb
ruco-0.0.49 lib/ruco/history.rb
ruco-0.0.48 lib/ruco/history.rb
ruco-0.0.47 lib/ruco/history.rb
ruco-0.0.46 lib/ruco/history.rb
ruco-0.0.45 lib/ruco/history.rb
ruco-0.0.44 lib/ruco/history.rb
ruco-0.0.43 lib/ruco/history.rb
ruco-0.0.42 lib/ruco/history.rb
ruco-0.0.41 lib/ruco/history.rb
ruco-0.0.40 lib/ruco/history.rb
ruco-0.0.39 lib/ruco/history.rb
ruco-0.0.38 lib/ruco/history.rb
ruco-0.0.37 lib/ruco/history.rb
ruco-0.0.36 lib/ruco/history.rb