Class: Toggly::Rails::CacheSnapshotProvider

Inherits:
SnapshotProviders::Base
  • Object
show all
Defined in:
lib/toggly/rails/cache_snapshot_provider.rb

Overview

Snapshot provider that uses Rails.cache.

Stores feature definitions in the Rails cache store for persistence and sharing across processes.

Instance Method Summary collapse

Constructor Details

#initialize(key_prefix: "toggly", expires_in: nil) ⇒ CacheSnapshotProvider

Returns a new instance of CacheSnapshotProvider.

Parameters:

  • key_prefix (String) (defaults to: "toggly")

    Cache key prefix

  • expires_in (Integer, nil) (defaults to: nil)

    Cache expiration in seconds (nil = no expiration)



12
13
14
15
16
# File 'lib/toggly/rails/cache_snapshot_provider.rb', line 12

def initialize(key_prefix: "toggly", expires_in: nil)
  super()
  @key_prefix = key_prefix
  @expires_in = expires_in
end

Instance Method Details

#clearObject

Clear the cached snapshot



48
49
50
# File 'lib/toggly/rails/cache_snapshot_provider.rb', line 48

def clear
  ::Rails.cache.delete(cache_key)
end

#exists?Boolean

Check if snapshot exists in cache

Returns:

  • (Boolean)


55
56
57
# File 'lib/toggly/rails/cache_snapshot_provider.rb', line 55

def exists?
  ::Rails.cache.exist?(cache_key)
end

#loadHash?

Load definitions from Rails cache

Returns:

  • (Hash, nil)

    Hash with :definitions and :metadata



37
38
39
40
41
42
43
44
45
# File 'lib/toggly/rails/cache_snapshot_provider.rb', line 37

def load
  data = ::Rails.cache.read(cache_key)
  return nil unless data

  {
    definitions: deserialize_definitions(data[:definitions]),
    metadata: data[:metadata] || {}
  }
end

#save(definitions, metadata = {}) ⇒ Object

Save definitions to Rails cache

Parameters:

  • definitions (Hash<String, FeatureDefinition>)

    Definitions

  • metadata (Hash) (defaults to: {})

    Optional metadata



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/toggly/rails/cache_snapshot_provider.rb', line 22

def save(definitions,  = {})
  data = {
    definitions: serialize_definitions(definitions),
    metadata: .merge(saved_at: Time.now.utc.iso8601)
  }

  cache_options = {}
  cache_options[:expires_in] = @expires_in if @expires_in

  ::Rails.cache.write(cache_key, data, **cache_options)
end