class Ki::KiJSONFile
Base implementation for json files.
-
DirectoryBase
takes a path argument where file will exist -
Classes inheriting this file should implement json_default() to define default data object
-
cached_data loads data from disk when first accessed and
edit_data
modifies it -
helper methods should access data through cached_data
Public Class Methods
load_json(path, default=nil)
click to toggle source
# File lib/data_storage/ki_json.rb, line 50 def KiJSONFile.load_json(path, default=nil) if File.exists?(path) JSON.parse(IO.read(path)) else default end end
Public Instance Methods
edit_data(&block)
click to toggle source
Loads data from file path, makes it editable and saves data
# File lib/data_storage/ki_json.rb, line 34 def edit_data(&block) @cached_data = load_data_from_file block.call(self) File.safe_write(path, JSON.pretty_generate(@cached_data)) @cached_data end
load_data_from_file(default=json_default)
click to toggle source
Loads latest data from file path. Does not update cached_data
# File lib/data_storage/ki_json.rb, line 29 def load_data_from_file(default=json_default) KiJSONFile.load_json(path, default) end
reset_cached_data()
click to toggle source
# File lib/data_storage/ki_json.rb, line 58 def reset_cached_data remove_instance_variable(:@cached_data) end
save(data=cached_data)
click to toggle source
Saves data to file path. Does not update cached_data
# File lib/data_storage/ki_json.rb, line 42 def save(data=cached_data) File.safe_write(path, JSON.pretty_generate(data)) end
size()
click to toggle source
# File lib/data_storage/ki_json.rb, line 46 def size cached_data.size end