Class: RailsControllerStatsd::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app, statsd_client = nil, stats_prefix = '') ⇒ Middleware

Initializes the middleware.

Parameters:

  • app

    The next Rack app in the pipeline.

  • statsd_client (defaults to: nil)

    Statsd client - optional

  • stats_prefix (defaults to: '')

    Prefix for the metrics - optional



11
12
13
14
15
# File 'lib/rails_controller_statsd.rb', line 11

def initialize(app, statsd_client = nil, stats_prefix = '')
  @app = app
  @statsd_client = statsd_client
  @stats_prefix = stats_prefix
end

Instance Method Details

#call(env) ⇒ Object

Rack entry point.

Parameters:

  • env (Hash)

    The next Rack app in the pipeline.



20
21
22
23
24
25
26
27
28
# File 'lib/rails_controller_statsd.rb', line 20

def call(env)
  controller_info = get_controller_info(env)

  unless @statsd_client.nil? || controller_info.empty?
    record_hit(controller_info)
  end

  @app.call(env)
end

#counter(controller_info) ⇒ String

Takes controller and action information and return the counter string

Parameters:

  • controller_info (Hash)

    { controller: ‘controller’, action: ‘action’}

Returns:

  • (String)


41
42
43
44
45
46
47
48
49
# File 'lib/rails_controller_statsd.rb', line 41

def counter(controller_info)
  prefix = if @stats_prefix
             "#{@stats_prefix}."
           else
             ''
           end

  prefix + "#{controller_info[:controller].gsub('/','.')}.#{controller_info[:action]}"
end

#get_controller_info(env) ⇒ Hash

Takes the Rack information and return the Rails Controller and Action

Parameters:

  • env (Hash)

    The next Rack app in the pipeline.

Returns:

  • (Hash)


55
56
57
58
# File 'lib/rails_controller_statsd.rb', line 55

def get_controller_info(env)
  request = Rack::Request.new(env)
  (Rails.application.routes.recognize_path(request.path, { method: env['REQUEST_METHOD'] }) rescue {}) || {}
end

#record_hit(controller_info) ⇒ Object

Increment the counter for the controller and action

Parameters:

  • controller_info (Hash)

    { controller: ‘controller’, action: ‘action’}



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

def record_hit(controller_info)
  @statsd_client.increment counter(controller_info)
end