Module: Sequel::Plugins::StaticCache

Defined in:
lib/sequel/plugins/static_cache.rb

Overview

The static_cache plugin is designed for models that are not modified at all in production use cases, or at least where modifications to them would usually coincide with an application restart. When loaded into a model class, it retrieves all rows in the database and statically caches a ruby array and hash keyed on primary key containing all of the model instances. All of these instances are frozen so they won’t be modified unexpectedly, and before hooks disallow saving or destroying instances.

You can use the :frozen=>false option to have this plugin return unfrozen instances. This is slower as it requires creating new objects, but it allows you to make changes to the object and save them. If you set the option to false, you are responsible for updating the cache manually (the pg_static_cache_updater extension can handle this automatically).

The caches this plugin creates are used for the following things:

  • Primary key lookups (e.g. Model)

  • Model.all

  • Model.each

  • Model.count (without an argument or block)

  • Model.map

  • Model.to_hash

  • Model.to_hash_groups

Usage:

# Cache the AlbumType class statically, disallowing any changes.
AlbumType.plugin :static_cache

# Cache the AlbumType class statically, but return unfrozen instances
# that can be modified.
AlbumType.plugin :static_cache, :frozen=>false

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.configure(model, opts = OPTS) ⇒ Object

Populate the static caches when loading the plugin. Options:

:frozen

Whether retrieved model objects are frozen. The default is true, for better performance as the shared frozen objects can be used directly. If set to false, new instances are created.



40
41
42
43
44
45
# File 'lib/sequel/plugins/static_cache.rb', line 40

def self.configure(model, opts=OPTS)
  model.instance_eval do
    @static_cache_frozen = opts.fetch(:frozen, true)
    load_cache
  end
end