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
# 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.

  @actions = @actions[0..@last_done] if can_redo?

  # 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.



76
77
78
79
80
81
82
83
# File 'lib/fidgit/history.rb', line 76

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)


55
56
57
58
59
60
61
62
63
# File 'lib/fidgit/history.rb', line 55

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.



66
67
68
69
70
71
72
73
# File 'lib/fidgit/history.rb', line 66

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

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

  nil
end