class PerfectWorld::Storage

Public Class Methods

dump(data, recipient, path) click to toggle source

Writes data into an encrypted file.

PerfectWorld::Storage.dump([1, 2], 'gpguid', /path/to/file.yml.gpg')

Raises PerfectWorld::Error on error.

# File lib/perfect_world/storage.rb, line 27
def dump(data, recipient, path)
  commit(encrypt(serialize(data), find_key(recipient)), path)
end
find_key(term = nil) click to toggle source

Finds a secret key in the key ring.

Returns GPGME::Key or raises PerfectWorld::KeyNotFound.

# File lib/perfect_world/storage.rb, line 34
def find_key(term = nil)
  GPGME::Key.find(:secrect, term).first || raise(KeyNotFound, term)
end
load(path) click to toggle source

Loads data from an encrypted file.

PerfectWorld::Storage.load('path/to/file.yml.gpg')  #=> [1, 2]

Returns the data.

# File lib/perfect_world/storage.rb, line 16
def load(path)
  open(path) do |file|
    deserialize(decrypt(file))
  end
end

Private Class Methods

commit(data, path) click to toggle source
# File lib/perfect_world/storage.rb, line 49
def commit(data, path)
  File.open(path, File::RDWR|File::CREAT, 0600) do |f|
    f.flock(File::LOCK_EX)
    f.truncate(0)
    f.write(data)
  end
rescue SystemCallError, IOError => e
  raise Error, e.message
end
decrypt(data) click to toggle source
# File lib/perfect_world/storage.rb, line 77
def decrypt(data)
  GPGME::Crypto.new.decrypt(data) do |signature|
    raise(CorruptedDatabase, 'Invalid signature.') unless signature.valid?
  end.to_s
rescue GPGME::Error => e
  raise Error, e.message
end
deserialize(data) click to toggle source
# File lib/perfect_world/storage.rb, line 65
def deserialize(data)
  YAML.load(data)
rescue => e
  raise Error, e.message
end
encrypt(data, key) click to toggle source
# File lib/perfect_world/storage.rb, line 71
def encrypt(data, key)
  GPGME::Crypto.new.encrypt(data, recipients: key, sign: true, signers: key)
rescue GPGME::Error => e
  raise Error, e.message
end
open(path) { |f| ... } click to toggle source
# File lib/perfect_world/storage.rb, line 40
def open(path)
  File.open(path, 'r') do |f|
    f.flock(File::LOCK_SH)
    yield(f)
  end
rescue SystemCallError, IOError => e
  raise Error, e.message
end
serialize(data) click to toggle source
# File lib/perfect_world/storage.rb, line 59
def serialize(data)
  YAML.dump(data)
rescue => e
  raise Error, e.message
end