Class: TomatoHarvest::List
- Inherits:
-
Object
- Object
- TomatoHarvest::List
- Extended by:
- Forwardable
- Defined in:
- lib/tomatoharvest/list.rb
Instance Attribute Summary collapse
-
#items ⇒ Object
readonly
Returns the value of attribute items.
Class Method Summary collapse
Instance Method Summary collapse
- #add(item) ⇒ Object
- #find(id) ⇒ Object
-
#initialize(path, items = nil) ⇒ List
constructor
A new instance of List.
- #load! ⇒ Object
- #remove(id) ⇒ Object
- #save! ⇒ Object
Constructor Details
#initialize(path, items = nil) ⇒ List
Returns a new instance of List.
16 17 18 19 |
# File 'lib/tomatoharvest/list.rb', line 16 def initialize(path, items = nil) @path = path @items = items || [] end |
Instance Attribute Details
#items ⇒ Object (readonly)
Returns the value of attribute items.
8 9 10 |
# File 'lib/tomatoharvest/list.rb', line 8 def items @items end |
Class Method Details
.init_and_load(*args) ⇒ Object
12 13 14 |
# File 'lib/tomatoharvest/list.rb', line 12 def self.init_and_load(*args) new(*args).load! end |
Instance Method Details
#add(item) ⇒ Object
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/tomatoharvest/list.rb', line 47 def add(item) if last_item = @items.last id = last_item.id else id = 0 end item.id = id + 1 @items << item end |
#find(id) ⇒ Object
29 30 31 32 33 |
# File 'lib/tomatoharvest/list.rb', line 29 def find(id) @items.find do |item| item.id == id.to_i end end |
#load! ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/tomatoharvest/list.rb', line 21 def load! if File.exists?(@path) && items = YAML.load_file(@path) @items = items end self end |
#remove(id) ⇒ Object
58 59 60 61 62 |
# File 'lib/tomatoharvest/list.rb', line 58 def remove(id) @items.delete_if do |item| item.id == id.to_i end end |
#save! ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tomatoharvest/list.rb', line 35 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 |