Class: Pwrb::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/pwrb/db.rb

Instance Method Summary collapse

Constructor Details

#initialize(filename, password) ⇒ DB

Returns a new instance of DB.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/pwrb/db.rb', line 7

def initialize(filename, password)
  @filename = filename
  @passwords = []
  @crypto = GPGME::Crypto.new

  # Read encrypted file
  if File.exist?(filename)
    text = @crypto.decrypt(File.open(filename), :password => password).to_s
    @passwords = JSON.parse(text, :symbolize_names => true)
  else
    FileUtils.mkdir_p(File.dirname(filename))
    save
    File.chmod(0600, filename)
  end
end

Instance Method Details

#insert(item) ⇒ Object



37
38
39
40
# File 'lib/pwrb/db.rb', line 37

def insert(item)
  @passwords << item.merge(:id => SecureRandom.uuid, :date => timestamp)
  save
end

#query(user, site) ⇒ Object



33
34
35
# File 'lib/pwrb/db.rb', line 33

def query(user, site)
  @passwords.select {|p| /#{user}/i =~ p[:user] && (/#{site}/i =~ p[:site] || /#{site}/i =~ p[:url]) }
end

#remove(item) ⇒ Object



51
52
53
54
# File 'lib/pwrb/db.rb', line 51

def remove(item)
  @passwords.delete(item)
  save
end

#saveObject



23
24
25
26
27
# File 'lib/pwrb/db.rb', line 23

def save
  text = JSON.generate(@passwords)
  text.force_encoding('ASCII-8BIT')
  @crypto.encrypt(text, :output => File.open(@filename, 'w+'))
end

#timestampObject



56
57
58
# File 'lib/pwrb/db.rb', line 56

def timestamp
  Date.today.strftime("%Y%m%d")
end

#to_sObject



29
30
31
# File 'lib/pwrb/db.rb', line 29

def to_s
  "<*>"
end

#update(new_item) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/pwrb/db.rb', line 42

def update(new_item)
  new_item.merge!(:date => timestamp)
  item = @passwords.find { |p| p[:id] == new_item[:id] }
  if item
    item.merge!(new_item) { |_, oldval, newval| (newval && !newval.empty?) ? newval : oldval }
    save
  end
end