class Wireless::SynchronizedStore

A Hash wrapper with synchronized get, set and check methods.

Public Class Methods

new(store = {}, replace: false, type: :key) click to toggle source
# 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

Public Instance Methods

[](key) click to toggle source

Retrieve a value from the store

A synchronized version of:

store[key]
# File lib/wireless/synchronized_store.rb, line 19
def [](key)
  @lock.synchronize { @store[key] }
end
[]=(key, value) click to toggle source

Add a key/value to the store

A synchronized version of:

store[key] = value
# 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!(key)
Alias for: get_or_create
get_or_create(key) { || ... } click to toggle source

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
# 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
Also aliased as: get!
include?(key) click to toggle source

Returns true if the store contains the key, false otherwise

A synchronized version of:

store.include?(key)
# File lib/wireless/synchronized_store.rb, line 76
def include?(key)
  @lock.synchronize { @store.include?(key) }
end