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). Note that it is not safe to use the :frozen=>false option if you are mutating column values directly. If you are mutating column values, you should also override Model.call to dup each mutable column value to ensure it is not shared by other instances.
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
If you would like the speed benefits of keeping :frozen=>true but still need to occasionally update objects, you can side-step the before_ hooks by overriding the class method static_cache_allow_modifications?
to return true:
class Model
plugin :static_cache
def self.static_cache_allow_modifications?
true
end
end
Now if you #dup
a Model object (the resulting object is not frozen), you will be able to update and save the duplicate. Note the caveats around your responsibility to update the cache still applies.
Defined Under Namespace
Modules: ClassMethods, InstanceMethods
Class Method Summary collapse
-
.configure(model, opts = OPTS) ⇒ Object
Populate the static caches when loading the plugin.
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.
60 61 62 63 64 65 |
# File 'lib/sequel/plugins/static_cache.rb', line 60 def self.configure(model, opts=OPTS) model.instance_eval do @static_cache_frozen = opts.fetch(:frozen, true) load_cache end end |