Created
August 16, 2020 13:15
-
-
Save ksoda/2e725ec48201a82edbab3d9a2e6f056c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class SimpleKvs # :nodoc: | |
def self.call(file_name) | |
raf = File.open(file_name, 'r+') | |
new(raf) | |
end | |
def initialize(raf) | |
@raf = raf | |
end | |
def set(key, value) | |
raf.seek(0, IO::SEEK_END) | |
raf.write("#{key}\t") | |
raf.write("#{Marshal.dump(value)}\n") | |
nil | |
end | |
def get(key) | |
line = seek(key) | |
return unless line | |
Marshal.load(line.split("\t").last) # rubocop:disable Security/MarshalLoad | |
end | |
private | |
attr_reader :raf | |
def seek(key) | |
raf.rewind | |
raf.readlines.reverse.find { |i| i.start_with?("#{key}\t") } | |
end | |
end | |
def main | |
name = './db.txt' | |
File.write(name, '') unless File.exist?(name) | |
kvs = SimpleKvs.call(name) | |
kvs.set('k', 1) | |
kvs.set('s', 2) | |
end | |
if File.identical?(__FILE__, $PROGRAM_NAME) | |
require 'minitest/spec' | |
require 'minitest/autorun' | |
require 'stringio' | |
describe SimpleKvs do | |
let(:kvs) { SimpleKvs.new(StringIO.new) } | |
it 'set and get' do | |
kvs.set('k', 1) | |
kvs.set('s', 2) | |
_(kvs.get('k')).must_equal 1 | |
_(kvs.get('s')).must_equal 2 | |
kvs.set('k', 3) | |
_(kvs.get('k')).must_equal 3 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment