Class: RailsNamedCache::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_named_cache/registry.rb

Overview

Thread-safe store of named ActiveSupport::Cache::Store instances.

Lookups are O(1) and lock-free; writes happen once during boot.

Examples:

registry = RailsNamedCache::Registry.new
registry.register(:memory, ActiveSupport::Cache::MemoryStore.new)
registry.fetch(:memory) # => #<ActiveSupport::Cache::MemoryStore>

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



15
16
17
# File 'lib/rails_named_cache/registry.rb', line 15

def initialize
  @stores = Concurrent::Map.new
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Removes every registered store. Intended for tests and reboots.



66
67
68
# File 'lib/rails_named_cache/registry.rb', line 66

def clear
  @stores.clear
end

#fetch(name) ⇒ ActiveSupport::Cache::Store

Parameters:

  • name (Symbol, String)

    registered store name

Returns:

  • (ActiveSupport::Cache::Store)

Raises:



41
42
43
44
# File 'lib/rails_named_cache/registry.rb', line 41

def fetch(name)
  key = RailsNamedCache.normalize_name(name)
  @stores.fetch(key) { raise UnknownStoreError.new(key, names) }
end

#namesArray<Symbol>

Returns every registered name.

Returns:

  • (Array<Symbol>)

    every registered name



54
55
56
# File 'lib/rails_named_cache/registry.rb', line 54

def names
  @stores.keys
end

#register(name, store) ⇒ ActiveSupport::Cache::Store

Registers store under name, replacing any previous entry.

Parameters:

  • name (Symbol, String)

    name used by Rails.cache(name)

  • store (ActiveSupport::Cache::Store)

    the store instance

Returns:

  • (ActiveSupport::Cache::Store)

    the registered store

Raises:



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rails_named_cache/registry.rb', line 25

def register(name, store)
  key = RailsNamedCache.normalize_name(name)

  unless store.is_a?(ActiveSupport::Cache::Store)
    raise ConfigurationError,
          "Named cache store #{key.inspect} must be an ActiveSupport::Cache::Store, " \
          "got #{store.class}"
  end

  @stores[key] = store
end

#registered?(name) ⇒ Boolean

Parameters:

  • name (Symbol, String)

Returns:

  • (Boolean)

Raises:



49
50
51
# File 'lib/rails_named_cache/registry.rb', line 49

def registered?(name)
  @stores.key?(RailsNamedCache.normalize_name(name))
end

#sizeInteger

Returns number of registered stores.

Returns:

  • (Integer)

    number of registered stores



59
60
61
# File 'lib/rails_named_cache/registry.rb', line 59

def size
  @stores.size
end

#to_hHash{Symbol=>ActiveSupport::Cache::Store}

Returns snapshot of the registry.

Returns:

  • (Hash{Symbol=>ActiveSupport::Cache::Store})

    snapshot of the registry



71
72
73
# File 'lib/rails_named_cache/registry.rb', line 71

def to_h
  @stores.each_pair.to_h
end