class PerfectWorld::DB
Handles the password database.
Public Class Methods
Loads the database.
# File lib/perfect_world/db.rb, line 22 def self.load(path) passwords = Storage.load(path) valid?(passwords) ? new(passwords) : raise(CorruptedDatabase, path) rescue Error => e raise Error, "Couldn't load database: #{e.message}" end
Inits the db and sets the initial passwords.
# File lib/perfect_world/db.rb, line 39 def initialize(passwords = {}) @passwords = passwords @changed = false end
# File lib/perfect_world/db.rb, line 10 def self.open(path, owner = nil) db = File.exist?(path) ? load(path) : new({}) if block_given? yield(db) db.save(path, owner) if db.changed? else db end end
Checks if a password hash is valid. A valid object is a hash with string values.
Returns true if it is valid else false.
# File lib/perfect_world/db.rb, line 34 def self.valid?(data) data.is_a?(Hash) && data.values.all? { |v| v.is_a?(String) } end
Public Instance Methods
Returns the password for the id or nil, if not found.
# File lib/perfect_world/db.rb, line 70 def [](id) @passwords[id] end
Returns true, when the database has changed, else false.
# File lib/perfect_world/db.rb, line 96 def changed? @changed end
Deletes the password from the database.
store.delete(:google) #=> "B6m/![)A%fqw,\\ti-d`4\"&0>gl+>$0$Z" store[:google] #=> nil
Returns nil if not found.
# File lib/perfect_world/db.rb, line 88 def delete(id) if (password = @passwords.delete(id)) @changed = true password end end
Iterates over all passwords.
store.each do |id, password| puts "#{password} #{id}" end
Returns an enumerator, if no block is given.
# File lib/perfect_world/db.rb, line 107 def each(&block) @passwords.each(&block) end
Fetches a password from the database. It behaves like Hash#fetch.
# File lib/perfect_world/db.rb, line 75 def fetch(id, *default) @passwords.fetch(id, *default) end
Generates a new password and puts it in the database.
store.generate(:google, 32) #=> "B6m/![)A%fqw,\\ti-d`4\"&0>gl+>$0$Z" store[:google] #=> "B6m/![)A%fqw,\\ti-d`4\"&0>gl+>$0$Z"
Returns the new password or raises an error if the password is already in the database.
# File lib/perfect_world/db.rb, line 54 def generate(id, len = 64) if ! @passwords.key?(id) generate!(id, len) else raise Error, "Your #{id} password is already in the database." end end
Does the same as DB#generate
, but overrides existing passwords.
# File lib/perfect_world/db.rb, line 63 def generate!(id, len = 64) @passwords[id] = Random.string(len) @changed = true @passwords[id] end
Encryptes the database and writes it to disk.
# File lib/perfect_world/db.rb, line 112 def save(path, owner = nil) Storage.dump(@passwords, owner, path) rescue Error => e raise Error, "Couldn't save database: #{e.message}" end