Class: ActiveRecordProxyAdapters::Context

Inherits:
Object
  • Object
show all
Includes:
Mixin::Configuration
Defined in:
lib/active_record_proxy_adapters/context.rb

Overview

Context is a simple class that holds a registry of connection names and their last write timestamps. It is used to track the last time a write operation was performed on each connection. This allows the proxy to determine whether to route read requests to the primary or replica database

Instance Method Summary collapse

Methods included from Mixin::Configuration

#cache_key_for, #cache_store, #checkout_timeout, #context_store, #log_subscriber_prefix, #logger, #proxy_delay, #regexp_timeout_strategy

Constructor Details

#initialize(hash) ⇒ Context

Returns a new instance of Context.

Parameters:

  • hash (Hash)

    A hash containing the connection names as keys and the last write timestamps as values. Can be empty.



14
15
16
# File 'lib/active_record_proxy_adapters/context.rb', line 14

def initialize(hash)
  @timestamp_registry = hash.transform_values(&:to_f)
end

Instance Method Details

#[](connection_name) ⇒ Object



26
27
28
# File 'lib/active_record_proxy_adapters/context.rb', line 26

def [](connection_name)
  timestamp_registry[connection_name.to_s] || 0
end

#[]=(connection_name, timestamp) ⇒ Object



30
31
32
# File 'lib/active_record_proxy_adapters/context.rb', line 30

def []=(connection_name, timestamp)
  timestamp_registry[connection_name.to_s] = timestamp
end

#recent_write_to_primary?(connection_name) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/active_record_proxy_adapters/context.rb', line 18

def recent_write_to_primary?(connection_name)
  now - self[connection_name.to_s] < proxy_delay(connection_name)
end

#to_hObject



34
35
36
# File 'lib/active_record_proxy_adapters/context.rb', line 34

def to_h
  timestamp_registry.dup
end

#update_for(connection_name) ⇒ Object



22
23
24
# File 'lib/active_record_proxy_adapters/context.rb', line 22

def update_for(connection_name)
  self[connection_name.to_s] = now
end