Class: KhoinguyenEhTodoList::Caretaker

Inherits:
Object
  • Object
show all
Defined in:
lib/khoinguyen_eh_todo_list/caretaker.rb

Overview

Caretaker class to manage the undo and redo history

Constant Summary collapse

UNDO_FILE =
"undo_history.yml"
REDO_FILE =
"redo_history.yml"

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Caretaker

Returns a new instance of Caretaker.



11
12
13
14
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 11

def initialize
  @undo_history = load_history(UNDO_FILE)
  @redo_history = load_history(REDO_FILE)
end

Instance Method Details

#add_memento(memento) ⇒ Object

Adds a memento to the undo history and saves to file

Parameters:



18
19
20
21
22
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 18

def add_memento(memento)
  @undo_history.push(memento)
  save_history(@undo_history, UNDO_FILE)
  clear_redo_history # Clear redo history when a new action is added
end

#clear_redo_history ⇒ Object

Clears the redo history



45
46
47
48
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 45

def clear_redo_history
  @redo_history.clear
  save_history(@redo_history, REDO_FILE)
end

#redo ⇒ Memento?

Returns the last memento from the redo history

Returns:



36
37
38
39
40
41
42
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 36

def redo
  memento = @redo_history.pop
  save_history(@redo_history, REDO_FILE)
  @undo_history.push(memento) if memento
  save_history(@undo_history, UNDO_FILE)
  memento
end

#redo_history_count ⇒ Integer

Returns the history count for redo

Returns:

  • (Integer)


58
59
60
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 58

def redo_history_count
  @redo_history.size
end

#undo ⇒ Memento?

Returns the last memento from the undo history

Returns:



26
27
28
29
30
31
32
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 26

def undo
  memento = @undo_history.pop
  save_history(@undo_history, UNDO_FILE)
  @redo_history.push(memento) if memento
  save_history(@redo_history, REDO_FILE)
  memento
end

#undo_history_count ⇒ Integer

Returns the history count for undo

Returns:

  • (Integer)


52
53
54
# File 'lib/khoinguyen_eh_todo_list/caretaker.rb', line 52

def undo_history_count
  @undo_history.size
end