Class: Wireless::SynchronizedStore
- Inherits:
-
Object
- Object
- Wireless::SynchronizedStore
- Defined in:
- lib/wireless/synchronized_store.rb
Overview
A Hash wrapper with synchronized get, set and check methods.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Retrieve a value from the store.
-
#[]=(key, value) ⇒ Object
Add a key/value to the store.
-
#get_or_create(key) ⇒ Object
(also: #get!)
Retrieve a value from the store.
-
#include?(key) ⇒ Boolean
Returns true if the store contains the key, false otherwise.
-
#initialize(store = {}, replace: false, type: :key) ⇒ SynchronizedStore
constructor
A new instance of SynchronizedStore.
Constructor Details
#initialize(store = {}, replace: false, type: :key) ⇒ SynchronizedStore
Returns a new instance of SynchronizedStore.
6 7 8 9 10 11 |
# File 'lib/wireless/synchronized_store.rb', line 6 def initialize(store = {}, replace: false, type: :key) @type = type @replace = replace @store = store @lock = Mutex.new end |
Instance Method Details
#[](key) ⇒ Object
Retrieve a value from the store
A synchronized version of:
store[key]
19 20 21 |
# File 'lib/wireless/synchronized_store.rb', line 19 def [](key) @lock.synchronize { @store[key] } end |
#[]=(key, value) ⇒ Object
Add a key/value to the store
A synchronized version of:
store[key] = value
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/wireless/synchronized_store.rb', line 29 def []=(key, value) @lock.synchronize do if !@replace && @store.include?(key) # XXX don't expose the receiver as this class is an internal # implementation detail raise Wireless::KeyError.new( "#{@type} already exists: #{key}", key: key ) end @store[key] = value end end |
#get_or_create(key) ⇒ Object Also known as: get!
Retrieve a value from the store. If it doesn’t exist and a block is supplied, create and return it; otherwise, raise a KeyError.
A synchronized version of:
store[key] ||= value
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/wireless/synchronized_store.rb', line 51 def get_or_create(key) @lock.synchronize do if @store.include?(key) @store[key] elsif block_given? @store[key] = yield else # XXX don't expose the receiver as this class is an internal # implementation detail raise Wireless::KeyError.new( "#{@type} not found: #{key}", key: key ) end end end |
#include?(key) ⇒ Boolean
Returns true if the store contains the key, false otherwise
A synchronized version of:
store.include?(key)
76 77 78 |
# File 'lib/wireless/synchronized_store.rb', line 76 def include?(key) @lock.synchronize { @store.include?(key) } end |