Class: MittensUi::Store
- Inherits:
-
Object
- Object
- MittensUi::Store
- Defined in:
- lib/mittens_ui/store.rb
Overview
A simple persistent key-value store backed by a JSON file. Data is saved to ~/.local/share/mittens_ui/<app_name>.json and automatically reloaded on the next instantiation.
Instance Method Summary collapse
-
#all ⇒ Hash
Returns all stored key-value pairs with symbol keys.
-
#clear ⇒ void
Removes all data from the store and persists the change to disk.
-
#delete(key) ⇒ Object?
Deletes a key from the store and persists the change to disk.
-
#get(key, default = nil) ⇒ Object?
Retrieves a value by key.
-
#include?(key) ⇒ Boolean
Checks whether a key exists in the store.
-
#initialize(app_name) ⇒ Store
constructor
Creates a new store for the given app name.
-
#set(key, value) ⇒ Object
Stores a value under the given key and persists it to disk.
Constructor Details
#initialize(app_name) ⇒ Store
Creates a new store for the given app name. If a store file already exists for this app, it will be loaded automatically.
28 29 30 31 32 33 |
# File 'lib/mittens_ui/store.rb', line 28 def initialize(app_name) @app_name = app_name @path = File.join(data_dir, "#{app_name}.json") FileUtils.mkdir_p(data_dir) @data = load end |
Instance Method Details
#all ⇒ Hash
Returns all stored key-value pairs with symbol keys.
89 90 91 |
# File 'lib/mittens_ui/store.rb', line 89 def all @data.transform_keys(&:to_sym) end |
#clear ⇒ void
This method returns an undefined value.
Removes all data from the store and persists the change to disk.
100 101 102 103 |
# File 'lib/mittens_ui/store.rb', line 100 def clear @data = {} persist end |
#delete(key) ⇒ Object?
Deletes a key from the store and persists the change to disk. Returns nil if the key does not exist.
76 77 78 79 80 |
# File 'lib/mittens_ui/store.rb', line 76 def delete(key) value = @data.delete(key.to_s) persist value end |
#get(key, default = nil) ⇒ Object?
Retrieves a value by key. Returns the default value if the key does not exist. Symbol and string keys are treated as equivalent.
63 64 65 |
# File 'lib/mittens_ui/store.rb', line 63 def get(key, default = nil) @data.fetch(key.to_s, default) end |
#include?(key) ⇒ Boolean
Checks whether a key exists in the store. Symbol and string keys are treated as equivalent.
114 115 116 |
# File 'lib/mittens_ui/store.rb', line 114 def include?(key) @data.key?(key.to_s) end |
#set(key, value) ⇒ Object
Stores a value under the given key and persists it to disk. Symbol and string keys are treated as equivalent. Values must be JSON serializable (String, Integer, Float, Boolean, Array, Hash).
46 47 48 49 50 |
# File 'lib/mittens_ui/store.rb', line 46 def set(key, value) @data[key.to_s] = value persist value end |