Class: Bmo2::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/bmo2/storage.rb

Constant Summary collapse

JSON_FILE =
"#{ENV['HOME']}/.bmo2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStorage

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

#listsObject



17
18
19
# File 'lib/bmo2/storage.rb', line 17

def lists
  @lists.sort_by { |list| -list.items.size }
end

Instance Method Details

#bootstrapObject



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

Returns:

  • (Boolean)


29
30
31
# File 'lib/bmo2/storage.rb', line 29

def item_exists?(name)
  items.detect { |item| item.name == name }
end

#itemsObject



25
26
27
# File 'lib/bmo2/storage.rb', line 25

def items
  @lists.collect(&:items).flatten
end

#json_fileObject



5
6
7
# File 'lib/bmo2/storage.rb', line 5

def json_file
  ENV['BMO2MFILE'] || JSON_FILE
end

#list_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/bmo2/storage.rb', line 21

def list_exists?(name)
  @lists.detect { |list| list.name == name }
end

#populateObject



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

#saveObject



61
62
63
# File 'lib/bmo2/storage.rb', line 61

def save
  File.open(json_file, 'w') {|f| f.write(to_json) }
end

#to_hashObject



33
34
35
# File 'lib/bmo2/storage.rb', line 33

def to_hash
  { :lists => lists.collect(&:to_hash) }
end

#to_jsonObject



65
66
67
# File 'lib/bmo2/storage.rb', line 65

def to_json
  Yajl::Encoder.encode(to_hash, :pretty => true)
end