Class: Togul::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/togul/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Client

Returns a new instance of Client.

Parameters:



10
11
12
13
14
# File 'lib/togul/client.rb', line 10

def initialize(config)
  @config = config
  @cache = Cache.new(ttl: config.cache_ttl)
  @stream_client = nil
end

Instance Method Details

#enabled?(key, context = {}) ⇒ Boolean

Evaluate a feature flag.

Parameters:

  • key (String)

    Flag key

  • context (Hash<String, String>) (defaults to: {})

    User/request context

Returns:

  • (Boolean)

    Whether the flag is enabled



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/togul/client.rb', line 21

def enabled?(key, context = {})
  cache_key = build_cache_key(key, context)

  cached = @cache.get(cache_key)
  return cached unless cached.nil?

  value = evaluate(key, context)
  @cache.set(cache_key, value)
  value
rescue StandardError
  case @config.fallback_mode
  when :fail_open then true
  else false
  end
end

#invalidate_cacheObject

Clear all cached flag values.



38
39
40
# File 'lib/togul/client.rb', line 38

def invalidate_cache
  @cache.flush
end

#invalidate_flag(key) ⇒ Object

Clear a specific flag from cache.



43
44
45
# File 'lib/togul/client.rb', line 43

def invalidate_flag(key)
  @cache.invalidate_flag(key)
end

#on_cache_invalidated(&block) ⇒ Object

Register a listener for cache invalidation events.



53
54
55
# File 'lib/togul/client.rb', line 53

def on_cache_invalidated(&block)
  stream.on_cache_invalidated(&block)
end

#streamObject

Start SSE stream for real-time cache invalidation.



48
49
50
# File 'lib/togul/client.rb', line 48

def stream
  @stream_client ||= StreamClient.new(@config, @cache)
end