lib/tomatoharvest/list.rb in tomatoharvest-0.0.1 vs lib/tomatoharvest/list.rb in tomatoharvest-0.1.0

- old
+ new

@@ -1,50 +1,49 @@ require 'yaml' +require 'forwardable' module TomatoHarvest class List - PATH = File.expand_path("#{ENV['$HOME']}/.toma") + extend ::Forwardable attr_reader :items - alias :all :items + def_delegators :items, :count, :map - def self.add(item) - new.tap do |list| - list.add(item) - list.save - end + def self.init_and_load(*args) + new(*args).load! end - def self.all - new.all + def initialize(path, items = nil) + @path = path + @items = items || [] end - def self.find(id) - new.find(id) - end - - def initialize - if File.exists?(PATH) - @items = load_list - else - @items = [] + def load! + if File.exists?(@path) && items = YAML.load_file(@path) + @items = items end + + self end def find(id) - # TODO speed this up with an algo - all.find do |item| + @items.find do |item| item.id == id.to_i end end - def save - yaml = YAML::dump(@items) - File.open(PATH, "w+") do |f| + def save! + dir = File.dirname(@path) + FileUtils.mkdir_p(dir) unless File.directory?(dir) + + yaml = YAML.dump(@items) + File.open(@path, "w+") do |f| f.write(yaml) end + + self end def add(item) if last_item = @items.last id = last_item.id @@ -54,23 +53,13 @@ item.id = id + 1 @items << item end - private - - def load_list - string = "" - - # better way to do this? - File.open(PATH, "r") do |f| - while line = f.gets - string += line - end + def remove(id) + @items.delete_if do |item| + item.id == id.to_i end - - YAML::load(string) end end end -