Class: Nunes::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/nunes/adapter.rb

Constant Summary collapse

ReplaceRegex =

Private: What Ruby uses to separate namespaces.

/[^a-z0-9\-_]+/i
Separator =

Private: The default metric namespace separator.

".".freeze
Nothing =

Private

"".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Adapter

Internal: Sets the client for the adapter.

client - The thing being adapted to a simple interface.



40
41
42
# File 'lib/nunes/adapter.rb', line 40

def initialize(client)
  @client = client
end

Instance Attribute Details

#clientObject (readonly)

Private



35
36
37
# File 'lib/nunes/adapter.rb', line 35

def client
  @client
end

Class Method Details

.adaptersObject

Private



30
31
32
# File 'lib/nunes/adapter.rb', line 30

def self.adapters
  [Nunes::Adapter, *subclasses]
end

.wrap(client) ⇒ Object

Private: Wraps a given object with the correct adapter/decorator.

client - The thing to be wrapped.

Returns Nunes::Adapter instance.

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/nunes/adapter.rb', line 10

def self.wrap(client)
  raise ArgumentError, "client cannot be nil" if client.nil?
  return client if client.is_a?(self)

  adapter = adapters.detect { |adapter| adapter.wraps?(client) }

  if adapter.nil?
    raise ArgumentError,
      "I have no clue how to wrap what you've given me (#{client.inspect})"
  end

  adapter.new(client)
end

.wraps?(client) ⇒ Boolean

Private

Returns:

  • (Boolean)


25
26
27
# File 'lib/nunes/adapter.rb', line 25

def self.wraps?(client)
  client.respond_to?(:increment) && client.respond_to?(:timing)
end

Instance Method Details

#increment(metric, value = 1) ⇒ Object

Internal: Increment a metric by a value. Override in subclass if client interface does not match.



46
47
48
# File 'lib/nunes/adapter.rb', line 46

def increment(metric, value = 1)
  @client.increment prepare(metric), value
end

#prepare(metric, replacement = Separator) ⇒ Object

Private: Prepare a metric name before it is sent to the adapter’s client.



66
67
68
69
70
71
72
73
74
# File 'lib/nunes/adapter.rb', line 66

def prepare(metric, replacement = Separator)
  escaped = Regexp.escape(replacement)
  replace_begin_end_regex = /\A#{escaped}|#{escaped}\Z/

  metric = metric.to_s.gsub(ReplaceRegex, replacement)
  metric.squeeze!(replacement)
  metric.gsub!(replace_begin_end_regex, Nothing)
  metric
end

#timing(metric, duration) ⇒ Object

Internal: Record a metric’s duration. Override in subclass if client interface does not match.



52
53
54
# File 'lib/nunes/adapter.rb', line 52

def timing(metric, duration)
  @client.timing prepare(metric), duration
end