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.

"."
Nothing =

Private

""

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.



38
39
40
# File 'lib/nunes/adapter.rb', line 38

def initialize(client)
  @client = client
end

Instance Attribute Details

#clientObject (readonly)

Private



33
34
35
# File 'lib/nunes/adapter.rb', line 33

def client
  @client
end

Class Method Details

.adaptersObject

Private



28
29
30
# File 'lib/nunes/adapter.rb', line 28

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)


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

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)


23
24
25
# File 'lib/nunes/adapter.rb', line 23

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.



44
45
46
# File 'lib/nunes/adapter.rb', line 44

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.



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

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.



50
51
52
# File 'lib/nunes/adapter.rb', line 50

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