class Petli::DB

Attributes

db[R]

Public Class Methods

new(path: "petli.pet") click to toggle source
# File lib/petli/db.rb, line 21
def initialize(path: "petli.pet")
  config_path = if !$petlidboverride.nil?
      $petlidboverride
    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

Public Instance Methods

clear() click to toggle source
# File lib/petli/db.rb, line 63
def clear
  del(*keys)
end
del(*args) click to toggle source
# File lib/petli/db.rb, line 59
def del(*args)
  db.transaction { args.each { |key| db.delete(key) } }
end
dump() click to toggle source
# File lib/petli/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) click to toggle source
# File lib/petli/db.rb, line 39
def exists?(key)
  db.transaction(true) { db.root?(key) }
end
get(key, default=nil) { || ... } click to toggle source
# File lib/petli/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() click to toggle source
# File lib/petli/db.rb, line 35
def keys
  db.transaction(true) { db.roots }
end
set(**args) click to toggle source
# File lib/petli/db.rb, line 43
def set(**args)
  db.transaction do
    args.each {|key, val| val.nil? ? db.delete(key) : db[key] = val}
  end
end