Class: UndoManager

Inherits:
Object
  • Object
show all
Defined in:
lib/undo_manager.rb,
lib/undo_manager/command.rb

Overview

Responsibilities

  • Manage undo stack

  • Manage redo stack

  • clear redo stack when new undo command is added

Collaborators

  • Command

Defined Under Namespace

Classes: Command

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(undo_stack = []) ⇒ UndoManager

Initializes a new UndoManager.

Parameters:

  • undo_stack (Array, optional) (defaults to: [])


13
14
15
16
17
# File 'lib/undo_manager.rb', line 13

def initialize(undo_stack = [])
  @undo_stack = undo_stack
  @redo_stack = []
  @total_ops_counter = 0
end

Instance Attribute Details

#redo_stackObject (readonly)

Returns the value of attribute redo_stack.



9
10
11
# File 'lib/undo_manager.rb', line 9

def redo_stack
  @redo_stack
end

#undo_stackObject (readonly)

Returns the value of attribute undo_stack.



9
10
11
# File 'lib/undo_manager.rb', line 9

def undo_stack
  @undo_stack
end

Instance Method Details

#can_redo?Boolean

Returns true if there is at least one command to be redone.

Returns:

  • (Boolean)


20
21
22
# File 'lib/undo_manager.rb', line 20

def can_redo?
  @redo_stack.any?
end

#can_undo?Boolean

Returns true if there is at least one command to be undone.

Returns:

  • (Boolean)


25
26
27
# File 'lib/undo_manager.rb', line 25

def can_undo?
  @undo_stack.any?
end

#record_new_command(command) ⇒ Integer

Pushes a new command onto the undo_stack.

Parameters:

  • command (#do, #undo)

    a command object that responds to #do and #undo

Returns:

  • (Integer)

    number of total commands



32
33
34
35
# File 'lib/undo_manager.rb', line 32

def record_new_command(command)
  @redo_stack = [] # clear redo stack
  @undo_stack.push(command)
end

#redo_commandCommand?

Redoes command at top of redo_stack.

Returns:

  • (Command, nil)

    the redone command or nil if nothing was redone



39
40
41
42
43
44
45
46
# File 'lib/undo_manager.rb', line 39

def redo_command
  o = @redo_stack.pop
  if o
    o.do # redo the command
    @undo_stack.push(o)
  end
  o
end

#undo_commandCommand?

Undoes command at top of undo_stack.

Returns:

  • (Command, nil)

    the undone command or nil if nothing was undone



50
51
52
53
54
55
56
57
# File 'lib/undo_manager.rb', line 50

def undo_command
  o = @undo_stack.pop
  if o
    o.undo # undo the command
    @redo_stack.push(o)
  end
  o
end