class TaskManager::TaskFile

Constants

CURRENT_NODE
DONE_NODE
ELEMENT
FILE_NAME
NEW_NODE
ROOT

Public Instance Methods

add(task) click to toggle source
# File lib/task_manager/task_file.rb, line 13
def add(task)
  node = create_node(task)
  handle_xml { root_node.add_child(node) }
  Task.new_from_node(node)
end
all() click to toggle source
# File lib/task_manager/task_file.rb, line 19
def all
  root_node.css(ELEMENT).map do |node|
    Task.new_from_node(node)
  end
end

Protected Instance Methods

create_file(file_name) click to toggle source
# File lib/task_manager/task_file.rb, line 63
def create_file(file_name)
  `touch #{file_name}`
end
create_node(task) click to toggle source
# File lib/task_manager/task_file.rb, line 27
def create_node(task)
  node = xml.create_element(ELEMENT)
  node['id']    = new_id
  node['name']  = task.name
  node['score'] = task.score
  node['created_at'] = task.created_at
  node['started_at'] = task.started_at
  node['finished_at'] = task.finished_at
  node
end
handle_xml() { || ... } click to toggle source
# File lib/task_manager/task_file.rb, line 67
def handle_xml
  yield if block_given?
  save_xml
end
highest_id() click to toggle source
# File lib/task_manager/task_file.rb, line 42
def highest_id
  root_node.css(ELEMENT).map { |node| node['id'] }.map(&:to_i).max || 0
end
new_id() click to toggle source
# File lib/task_manager/task_file.rb, line 38
def new_id
  highest_id + 1
end
root_node() click to toggle source
# File lib/task_manager/task_file.rb, line 53
def root_node
  @root_node ||= begin
    xml.css(ROOT).first || begin
      node = xml.create_element(ROOT)
      xml.add_child(node)
      node
    end
  end
end
save_xml() click to toggle source
# File lib/task_manager/task_file.rb, line 72
def save_xml
  File.open(FILE_NAME, 'w') { |f| f.write(xml.to_s) }
end
time_now() click to toggle source
# File lib/task_manager/task_file.rb, line 76
def time_now
  Time.now
end
xml() click to toggle source
# File lib/task_manager/task_file.rb, line 46
def xml
  @@xml ||= begin
    create_file(FILE_NAME) unless File.exists?(FILE_NAME)
    File.open(FILE_NAME, 'r') { |f| Nokogiri::XML(f) }
  end
end