Class: Bones::RPC::ReadPreference::Nearest

Inherits:
Object
  • Object
show all
Includes:
Selectable
Defined in:
lib/bones/rpc/read_preference/nearest.rb

Overview

Encapsulates behaviour around a nearest read preference.

Since:

  • 2.0.0

Instance Attribute Summary

Attributes included from Selectable

#tags

Instance Method Summary collapse

Methods included from Selectable

#initialize, #query_options

Instance Method Details

#nameSymbol

Get the name for the read preference on the server side.

Examples:

Get the name of the read preference.

nearest.name

Returns:

  • (Symbol)

    :nearest.

Since:

  • 2.0.0


20
21
22
# File 'lib/bones/rpc/read_preference/nearest.rb', line 20

def name
  :nearest
end

#with_node(cluster, &block) ⇒ Object

Note:

If tag sets are provided then selection will need to match the provided tags.

Execute the provided block on the node with the lowest latency, allowing either primary or secondary.

Examples:

Read from the nearest node in the cluster.

preference.with_node(cluster) do |node|
  node.command(ismaster: 1)
end

Parameters:

  • cluster (Cluster)

    The cluster of nodes to select from.

  • block (Proc)

    The block to execute on the node.

Returns:

  • (Object)

    The result of the block.

Raises:

Since:

  • 2.0.0


44
45
46
47
48
49
50
51
52
53
# File 'lib/bones/rpc/read_preference/nearest.rb', line 44

def with_node(cluster, &block)
  with_retry(cluster) do
    nearest = cluster.nodes.sort_by(&:latency).first
    if nearest
      block.call(nearest)
    else
      raise Errors::ConnectionFailure, "No nodes available to select in the cluster"
    end
  end
end