Class: Tatty::DB
- Inherits:
-
Object
- Object
- Tatty::DB
- Extended by:
- SingleForwardable
- Defined in:
- lib/tatty/db.rb
Defined Under Namespace
Modules: Attributes
Instance Attribute Summary collapse
-
#db ⇒ Object
readonly
Returns the value of attribute db.
Instance Method Summary collapse
- #clear ⇒ Object
- #del(*args) ⇒ Object
- #dump ⇒ Object
- #exists?(key) ⇒ Boolean
- #get(key, default = nil) ⇒ Object
-
#initialize ⇒ DB
constructor
A new instance of DB.
- #keys ⇒ Object
- #set(**args) ⇒ Object
Constructor Details
#initialize ⇒ DB
Returns a new instance of DB.
21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/tatty/db.rb', line 21 def initialize config_path = if !$tattydboverridepath.nil? $tattydboverridepath elsif TTY::Platform.windows? File.join(ENV["APPDATA"], 'petli', 'data.pet') elsif TTY::Platform.linux? File.join(ENV["XDG_CONFIG_DIRS"] || '/etc/xdg', 'petli', 'data.pet') elsif TTY::Platform.mac? File.join(File.('~/Library/Application Support'), 'petli', 'data.pet') end FileUtils.mkdir_p(File.dirname(config_path)) @db = PStore.new(config_path) end |
Instance Attribute Details
#db ⇒ Object (readonly)
Returns the value of attribute db.
19 20 21 |
# File 'lib/tatty/db.rb', line 19 def db @db end |
Instance Method Details
#clear ⇒ Object
63 64 65 |
# File 'lib/tatty/db.rb', line 63 def clear del(*keys) end |
#del(*args) ⇒ Object
59 60 61 |
# File 'lib/tatty/db.rb', line 59 def del(*args) db.transaction { args.each { |key| db.delete(key) } } end |
#dump ⇒ Object
67 68 69 70 71 72 73 74 75 |
# File 'lib/tatty/db.rb', line 67 def dump require 'json' begin file = File.new(@db.path, mode: IO::RDONLY | IO::BINARY, encoding: Encoding::ASCII_8BIT) JSON.dump(Marshal::load(file.read)) ensure file.close end end |
#exists?(key) ⇒ Boolean
39 40 41 |
# File 'lib/tatty/db.rb', line 39 def exists?(key) db.transaction(true) { db.root?(key) } end |
#get(key, default = nil) ⇒ Object
49 50 51 52 53 54 55 56 57 |
# File 'lib/tatty/db.rb', line 49 def get(key, default=nil) val = db.transaction(true) { db[key] } if val.nil? val = default unless default.nil? val = yield if block_given? db.transaction { db[key] = val } end val end |
#keys ⇒ Object
35 36 37 |
# File 'lib/tatty/db.rb', line 35 def keys db.transaction(true) { db.roots } end |
#set(**args) ⇒ Object
43 44 45 46 47 |
# File 'lib/tatty/db.rb', line 43 def set(**args) db.transaction do args.each {|key, val| val.nil? ? db.delete(key) : db[key] = val} end end |