Class: Wutang::Persistence

Inherits:
Object
  • Object
show all
Defined in:
lib/wutang/persistence.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, passphrase) ⇒ Persistence

Returns a new instance of Persistence.



5
6
7
8
9
# File 'lib/wutang/persistence.rb', line 5

def initialize(path, passphrase)
  @path   = File.expand_path(path)
  @crypto = Encryption.new(passphrase)
  Dir.mkdir(@path) unless File.exists?(@path)
end

Instance Attribute Details

#cryptoObject (readonly)

Returns the value of attribute crypto.



3
4
5
# File 'lib/wutang/persistence.rb', line 3

def crypto
  @crypto
end

#pathObject (readonly)

Returns the value of attribute path.



3
4
5
# File 'lib/wutang/persistence.rb', line 3

def path
  @path
end

Instance Method Details

#allObject



25
26
27
28
29
30
# File 'lib/wutang/persistence.rb', line 25

def all
  files.map do |file|
    content = read(file)
    Entry.new(content, file)
  end
end

#read(filename) ⇒ Object



11
12
13
14
15
16
# File 'lib/wutang/persistence.rb', line 11

def read(filename)
  data      = IO.read("#{path}/#{filename}.json")
  plaintext = crypto.decrypt(data)

  JSON.parse(plaintext, symbolize_names: true)
end

#write(filename, content) ⇒ Object



18
19
20
21
22
23
# File 'lib/wutang/persistence.rb', line 18

def write(filename, content)
  File.open("#{path}/#{filename}.json", "w") do |f|
    ciphertext = crypto.encrypt(content.to_json)
    f.write ciphertext
  end
end