Class: Boom::Storage::Json

Inherits:
Base
  • Object
show all
Includes:
Color, Output
Defined in:
lib/kaboom/storage/json.rb

Constant Summary collapse

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

Constants included from Color

Color::CODES

Instance Attribute Summary

Attributes inherited from Base

#lists

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Color

#colorize, included

Methods included from Output

#output

Methods inherited from Base

#handle, #initialize, #item_exists?, #items, #list_exists?, #to_hash

Constructor Details

This class inherits a constructor from Boom::Storage::Base

Class Method Details

.sample_configObject



22
23
24
# File 'lib/kaboom/storage/json.rb', line 22

def self.sample_config
  %({"backend":"json"})
end

Instance Method Details

#bootstrapObject

Takes care of bootstrapping the Json file, both in terms of creating the file and in terms of creating a skeleton Json schema.

Return true if successfully saved.



30
31
32
33
34
35
# File 'lib/kaboom/storage/json.rb', line 30

def bootstrap
  return if File.exist?(json_file)
  FileUtils.touch json_file
  File.open(json_file, 'w') {|f| f.write(to_json) }
  save
end

#json_fileObject

Public: the path to the Json file used by boom.

Returns the String path of boom’s Json representation.



17
18
19
20
# File 'lib/kaboom/storage/json.rb', line 17

def json_file

  JSON_FILE
end

#populateObject

Take a Json representation of data and explode it out into the consituent Lists and Items for the given Storage instance.

Returns nothing.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/kaboom/storage/json.rb', line 41

def populate
  storage = MultiJson.decode(File.new(json_file, 'r').read)

  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

Public: persists your in-memory objects to disk in Json format.

lists_Json - list in Json format

Returns true if successful, false if unsuccessful.



62
63
64
# File 'lib/kaboom/storage/json.rb', line 62

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

#to_jsonObject

Public: the Json representation of the current List and Item assortment attached to the Storage instance.

Returns a String Json representation of its Lists and their Items.



70
71
72
# File 'lib/kaboom/storage/json.rb', line 70

def to_json
  MultiJson.encode(to_hash)
end