Skip to content

Instantly share code, notes, and snippets.

/todo_list.rb Secret

Created April 8, 2016 03:02
Show Gist options
  • Save anonymous/b8f15882c8fcbad663c7a21b743fd430 to your computer and use it in GitHub Desktop.
Save anonymous/b8f15882c8fcbad663c7a21b743fd430 to your computer and use it in GitHub Desktop.
require 'observer'
# my attempt at the Observer Pattern based on:
# http://docs.ruby-lang.org/en/2.2.0/Observable.html
# ... and plenty of struggling
class TodoList
include Observable
attr_reader :title, :items
attr_accessor :todo_file
# Initialize todo list with a title and no items
def initialize(list_title)
@title = list_title
@items = []
add_observer(Watcher.new) # initialize Watcher class for Observer Pattern
end
# class methods for setting up file, writing to file, reading from file
def self.setup_file
@todo_file = File.new('program.txt', 'w+')
end
def self.write_to_file(text, file = @todo_file)
open(file, 'w+') { |f| f.puts text }
end
def self.read_from_file(file = @todo_file)
open(file, 'r') { |f| puts f.read }
end
def print_divider(length)
puts '-' * length
end
def print_todo
puts
puts
puts '%30s' % @title
print_divider 50
Item.print_items(@items)
end
# Creates a new Item and adds it to the array of Items
def add_item(new_item)
item = Item.new(new_item)
@items.push(item)
# notify Watcher of changes
changed
notify_observers(self, new_item)
end
# delete by number - get item by number, subtract one
# to get the correct array index
def delete_item(item_number)
@items.delete_at(item_number - 1) unless item_number == 0
# notify Watcher of changes
changed
notify_observers(self, item_number)
end
# get item by number, subtract one for correct array index
def get_item(item_number)
@items[(item_number - 1)]
end
# delete all items by resetting array to empty
def delete_all_items
@items = []
end
def update_title(title)
@title = title
# notify Watcher of changes
changed
notify_observers(self, title)
end
def make_time_stamp
Time.now.strftime('%m/%d/%Y')
end
def to_s
@title.to_s
end
end
class Item
include Observable
attr_reader :description, :completed_status
# Initialize item with a description and marked as not complete
def initialize(item_description)
@description = item_description
@completed_status = false
end
def mark_complete
@completed_status = true
# notify Watcher of changes
changed
notify_observers(self, completed_status) # not sure about second parameter
end
def completed?
@completed_status
end
def self.print_items(items)
items.each { |item| puts item }
end
def to_s
'%-25s Completed: %s' % [@description, completed?]
end
end
# class for using the Observer Pattern. (module Observable)
# write the Todo List to file every time that TodoList data changes
# ^ silently
class Watcher
def update(todolist, changed_data)
# write todolist to program.txt
TodoList.write_to_file(todolist.print_todo)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment