Class: Fidgit::History

Inherits:
Object show all
Defined in:
lib/fidgit/history.rb

Overview

Manages a history of actions, along with doing, undoing and redoing those actions.

Defined Under Namespace

Classes: Action

Constant Summary collapse

DEFAULT_MAX_SIZE =

Maximum number of actions in the History before Actions are deleted.

250

Instance Method Summary collapse

Constructor Details

#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ History

Returns a new instance of History.



24
25
26
27
28
# File 'lib/fidgit/history.rb', line 24

def initialize(max_size = DEFAULT_MAX_SIZE)
  @max_size = max_size
  @actions = []
  @last_done = -1 # Last command that was performed.
end

Instance Method Details

#can_redo?Boolean

Is there an action that has been undone that can now be redone?

Returns:

  • (Boolean)


22
# File 'lib/fidgit/history.rb', line 22

def can_redo?; @last_done < (@actions.size - 1); end

#can_undo?Boolean

Is there an action that can be undone?

Returns:

  • (Boolean)


19
# File 'lib/fidgit/history.rb', line 19

def can_undo?; @last_done >= 0; end

#do(action) ⇒ Object

Perform a History::Action, adding it to the history. If there are currently any actions that have been undone, they will be permanently lost and cannot be redone.

Parameters:

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fidgit/history.rb', line 34

def do(action)
  raise ArgumentError, "Parameter, 'action', expected to be a #{Action}, but received: #{action}" unless action.is_a? Action

  # Remove all undone actions when a new one is performed.
  if can_redo?
    if @last_done == -1
      @actions.clear
    else
      @actions = @actions[0..@last_done]
    end
  end

  # If history is too big, remove the oldest action.
  if @actions.size >= @max_size
    @actions.shift
  end

  @last_done = @actions.size
  @actions << action
  action.do

  nil
end

#redoObject

Redo the last action that was undone.



82
83
84
85
86
87
88
89
# File 'lib/fidgit/history.rb', line 82

def redo
  raise "Can't redo if there are no commands in the future" unless can_redo?

  @last_done += 1
  @actions[@last_done].do

  nil
end

#replace_last(action) ⇒ Object

Perform a History::Action, replacing the last action that was performed.

Parameters:

Raises:

  • (ArgumentError)


61
62
63
64
65
66
67
68
69
# File 'lib/fidgit/history.rb', line 61

def replace_last(action)
  raise ArgumentError, "Parameter, 'action', expected to be a #{Action}, but received: #{action}" unless action.is_a? Action

  @actions[@last_done].undo
  @actions[@last_done] = action
  action.do

  nil
end

#undoObject

Undo the last action that was performed.



72
73
74
75
76
77
78
79
# File 'lib/fidgit/history.rb', line 72

def undo
  raise "Can't undo unless there are commands in past" unless can_undo?

  @actions[@last_done].undo
  @last_done -= 1

  nil
end