Class: Safebox::File

Inherits:
Object
  • Object
show all
Defined in:
lib/safebox/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ File


3
4
5
# File 'lib/safebox/file.rb', line 3

def initialize(path)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path


7
8
9
# File 'lib/safebox/file.rb', line 7

def path
  @path
end

Instance Method Details

#read(password) {|version| ... } ⇒ Safebox::Hash

Returns read a hash, no matter the underlying file version.

Yields:

  • (version)

    yield the file version if it is not current.


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/safebox/file.rb', line 16

def read(password)
  if ::File.exist?(path)
    contents = ::File.read(path, encoding: Encoding::BINARY)

    [Safebox::VERSION, "0.1.0"].each do |version|
      hash = begin
        public_send(version, password, contents)
      rescue NoMethodError
        raise
      rescue => error
        $stderr.puts "Decryption failed for v#{version}: #{error}" if $DEBUG
        next
      end

      yield hash, version if version != Safebox::VERSION
      return hash
    end
  else
    Safebox::Hash.new(password)
  end
end

#write(hash) ⇒ Object


9
10
11
12
# File 'lib/safebox/file.rb', line 9

def write(hash)
  encoded = YAML.dump(hash.encrypted_hash)
  ::File.write(path, encoded, encoding: Encoding::BINARY)
end