Class: Tatty::DB

Inherits:
Object
  • Object
show all
Extended by:
SingleForwardable
Defined in:
lib/tatty/db.rb

Defined Under Namespace

Modules: Attributes

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDB

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.expand_path('~/Library/Application Support'), 'petli', 'data.pet')
    end
  FileUtils.mkdir_p(File.dirname(config_path))
  @db = PStore.new(config_path)
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



19
20
21
# File 'lib/tatty/db.rb', line 19

def db
  @db
end

Instance Method Details

#clearObject



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

#dumpObject



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

Returns:

  • (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

#keysObject



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