Class: Bmo2::Storage
- Inherits:
-
Object
- Object
- Bmo2::Storage
- Defined in:
- lib/bmo2/storage.rb
Constant Summary collapse
- JSON_FILE =
"#{ENV['HOME']}/.bmo2"
Instance Attribute Summary collapse
Instance Method Summary collapse
- #bootstrap ⇒ Object
-
#initialize ⇒ Storage
constructor
A new instance of Storage.
- #item_exists?(name) ⇒ Boolean
- #items ⇒ Object
- #json_file ⇒ Object
- #list_exists?(name) ⇒ Boolean
- #populate ⇒ Object
- #save ⇒ Object
- #to_hash ⇒ Object
- #to_json ⇒ Object
Constructor Details
#initialize ⇒ Storage
Returns a new instance of Storage.
9 10 11 12 13 |
# File 'lib/bmo2/storage.rb', line 9 def initialize @lists = [] bootstrap populate end |
Instance Attribute Details
#lists ⇒ Object
17 18 19 |
# File 'lib/bmo2/storage.rb', line 17 def lists @lists.sort_by { |list| -list.items.size } end |
Instance Method Details
#bootstrap ⇒ Object
37 38 39 40 41 42 |
# File 'lib/bmo2/storage.rb', line 37 def bootstrap return if File.exist?(json_file) and !File.zero?(json_file) FileUtils.touch json_file File.open(json_file, 'w') {|f| f.write(to_json) } save end |
#item_exists?(name) ⇒ Boolean
29 30 31 |
# File 'lib/bmo2/storage.rb', line 29 def item_exists?(name) items.detect { |item| item.name == name } end |
#items ⇒ Object
25 26 27 |
# File 'lib/bmo2/storage.rb', line 25 def items @lists.collect(&:items).flatten end |
#json_file ⇒ Object
5 6 7 |
# File 'lib/bmo2/storage.rb', line 5 def json_file ENV['BMO2MFILE'] || JSON_FILE end |
#list_exists?(name) ⇒ Boolean
21 22 23 |
# File 'lib/bmo2/storage.rb', line 21 def list_exists?(name) @lists.detect { |list| list.name == name } end |
#populate ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/bmo2/storage.rb', line 44 def populate file = File.new(json_file, 'r') storage = Yajl::Parser.parse(file) storage['lists'].each do |lists| lists.each do |list_name, items| @lists << list = List.new(list_name) items.each do |item| item.each do |name,value| list.add_item(Item.new(name,value)) end end end end end |
#save ⇒ Object
61 62 63 |
# File 'lib/bmo2/storage.rb', line 61 def save File.open(json_file, 'w') {|f| f.write(to_json) } end |
#to_hash ⇒ Object
33 34 35 |
# File 'lib/bmo2/storage.rb', line 33 def to_hash { :lists => lists.collect(&:to_hash) } end |
#to_json ⇒ Object
65 66 67 |
# File 'lib/bmo2/storage.rb', line 65 def to_json Yajl::Encoder.encode(to_hash, :pretty => true) end |