/fork-activesupport-cache-database

ActiveSupport::Cache::Store implementation backed by a database via ActiveRecord

Primary LanguageRubyApache License 2.0Apache-2.0

ActiveSupport::Cache::DatabaseStore

Test License

ActiveSupport::Cache::Store implementation backed by a database via ActiveRecord.

Tested with:

  • PostgreSQL
  • SQlite3
  • MySQL/MariaDB

Installation

Add this lin to you application's Gemfile: gem 'fork-activesupport-cache-database' And run: rails generate cache:database:install

Usage

Include the data migration:

# db/migrate/20190908102030_create_activesupport_cache_entries.rb
require 'active_support/cache/database_store/migration'

class CreateActivesupportCacheEntries < ActiveRecord::Migration[5.2]
  def up
    ActiveSupport::Cache::DatabaseStore::Migration.migrate(:up)
  end

  def down
    ActiveSupport::Cache::DatabaseStore::Migration.migrate(:down)
  end
end

Open and use the new cache instance:

cache = ActiveSupport::Cache::DatabaseStore.new namespace: 'my-scope'
value = cache.fetch('some-key') { 'default' }

To use as a Rails cache store, simply use a new instance. Please keep in mind that, for performance reasons, your database may not be the most suitable general purpose cache backend.

config.cache_store = ActiveSupport::Cache::DatabaseStore.new