Created
July 14, 2018 08:31
-
-
Save OPhamster/aed051a06a3b15c71e9a6e81a580d07d 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 SafeHash < Hash | |
def initialize(namespace) | |
@namespace = namespace | |
@lock = Concurrent::ReadWriteLock.new | |
super | |
merge!({ @namespace => Concurrent::Map.new }) | |
end | |
def []=(key, value) | |
fetch(@namespace, {})[key] = value | |
end | |
def [](key) | |
fetch(@namespace, {})[key] | |
end | |
def size | |
fetch(@namespace, {}).size | |
end | |
def keys | |
fetch(@namespace, {}).keys | |
end | |
def values | |
fetch(@namespace, {}).values | |
end | |
def clear | |
fetch(@namespace, {}).clear | |
end | |
def copy_and_clear | |
copy = {} | |
@lock.with_write_lock do | |
copy = delete(@namespace) | |
merge!({ @namespace => Concurrent::Map.new }) | |
end | |
return copy | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment