diff options
| author | mo khan <mo.khan@gmail.com> | 2020-11-21 16:19:45 -0700 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-11-21 16:19:45 -0700 |
| commit | cd2a844cce5240021cec23d75dce9550953107b3 (patch) | |
| tree | f66a0617738ef986761a0f0de560f17d0d93d80e | |
| parent | 73504a6b17408758155da297f4f1d78f31f7c4ca (diff) | |
feat: extract Storage class and lock shared resource
| -rw-r--r-- | lib/server.rb | 6 | ||||
| -rw-r--r-- | lib/storage.rb | 30 |
2 files changed, 33 insertions, 3 deletions
diff --git a/lib/server.rb b/lib/server.rb index 1d4706c..a5c25ab 100644 --- a/lib/server.rb +++ b/lib/server.rb @@ -1,12 +1,12 @@ -#!/usr/bin/env ruby require 'digest' -require 'rack' require 'json' +require 'rack' +require 'storage' class DataStorageServer MAX_BYTES=4096 - def initialize(storage: {}) + def initialize(storage: Storage.new) @storage = storage end diff --git a/lib/storage.rb b/lib/storage.rb new file mode 100644 index 0000000..57b2548 --- /dev/null +++ b/lib/storage.rb @@ -0,0 +1,30 @@ +class Storage + def initialize(storage: {}) + @storage = storage + @mutex = Mutex.new + end + + def key?(key) + with_lock { @storage.key?(key) } + end + + def [](key) + with_lock { @storage[key] } + end + + def []=(key, value) + with_lock { @storage[key] = value } + end + + def delete(key) + with_lock { @storage.delete(key) } + end + + private + + def with_lock + @mutex.synchronize do + yield + end + end +end |
