Class: ActiveRecord::Middleware::DatabaseSelector::Resolver

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/middleware/database_selector/resolver.rb,
lib/active_record/middleware/database_selector/resolver/session.rb

Overview

The Resolver class is used by the DatabaseSelector middleware to determine which database the request should use.

To change the behavior of the Resolver class in your application, create a custom resolver class that inherits from DatabaseSelector::Resolver and implements the methods that need to be changed.

By default the Resolver class will send read traffic to the replica if it’s been 2 seconds since the last write.

Defined Under Namespace

Classes: Session

Constant Summary collapse

SEND_TO_REPLICA_DELAY =

:nodoc:

2.seconds

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, options = {}) ⇒ Resolver

Returns a new instance of Resolver.



25
26
27
28
29
30
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 25

def initialize(context, options = {})
  @context = context
  @options = options
  @delay = @options && @options[:delay] ? @options[:delay] : SEND_TO_REPLICA_DELAY
  @instrumenter = ActiveSupport::Notifications.instrumenter
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



32
33
34
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 32

def context
  @context
end

#delayObject (readonly)

Returns the value of attribute delay.



32
33
34
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 32

def delay
  @delay
end

#instrumenterObject (readonly)

Returns the value of attribute instrumenter.



32
33
34
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 32

def instrumenter
  @instrumenter
end

Class Method Details

.call(context, options = {}) ⇒ Object



21
22
23
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 21

def self.call(context, options = {})
  new(context, options)
end

Instance Method Details

#read(&blk) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 34

def read(&blk)
  if read_from_primary?
    read_from_primary(&blk)
  else
    read_from_replica(&blk)
  end
end

#write(&blk) ⇒ Object



42
43
44
# File 'lib/active_record/middleware/database_selector/resolver.rb', line 42

def write(&blk)
  write_to_primary(&blk)
end