Class: Ki::KiJSONFile
- Inherits:
-
DirectoryBase
- Object
- DirectoryBase
- Ki::KiJSONFile
- Defined in:
- lib/data_storage/ki_json.rb
Overview
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
Direct Known Subclasses
Class Method Summary collapse
Instance Method Summary collapse
-
#edit_data(&block) ⇒ Object
Loads data from file path, makes it editable and saves data.
-
#load_data_from_file(default = json_default) ⇒ Object
Loads latest data from file path.
- #reset_cached_data ⇒ Object
-
#save(data = cached_data) ⇒ Object
Saves data to file path.
- #size ⇒ Object
Methods inherited from DirectoryBase
#child, #empty?, #exists?, find!, #go, #init_from_path, #initialize, #ki_path, #mkdir, #name, #path, #root, #root?
Constructor Details
This class inherits a constructor from Ki::DirectoryBase
Class Method Details
.load_json(path, default = nil) ⇒ Object
50 51 52 53 54 55 56 |
# 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 |
Instance Method Details
#edit_data(&block) ⇒ Object
Loads data from file path, makes it editable and saves data
34 35 36 37 38 39 |
# 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) ⇒ Object
Loads latest data from file path. Does not update cached_data
29 30 31 |
# 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 ⇒ Object
58 59 60 |
# File 'lib/data_storage/ki_json.rb', line 58 def reset_cached_data remove_instance_variable(:@cached_data) end |
#save(data = cached_data) ⇒ Object
Saves data to file path. Does not update cached_data
42 43 44 |
# File 'lib/data_storage/ki_json.rb', line 42 def save(data=cached_data) File.safe_write(path, JSON.pretty_generate(data)) end |
#size ⇒ Object
46 47 48 |
# File 'lib/data_storage/ki_json.rb', line 46 def size cached_data.size end |