Skip to content

Instantly share code, notes, and snippets.

@benolee
Forked from OPhamster/safe_hash.rb
Created February 4, 2019 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benolee/3efcad6c4921f8b1f8855aac740e9123 to your computer and use it in GitHub Desktop.
Save benolee/3efcad6c4921f8b1f8855aac740e9123 to your computer and use it in GitHub Desktop.
# 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