Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created November 15, 2011 22:22
Show Gist options
  • Save myronmarston/1368573 to your computer and use it in GitHub Desktop.
Save myronmarston/1368573 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
# so all actions get some basic logging
# this also makes the :log_metrics_for class macro method available to all controllers
include MetricLoggable
end
module MetricLoggable
extend ActiveSupport::Concern
included do
after_filter :log_action_metrics
end
private
def log_action_metrics
MyLogger.write(action_metrics)
end
def action_metrics
# We use instance_eval so `self` in the block is the current controller instance.
# That way, instance variables can be used.
base_metrics.merge instance_eval(&self.class.metric_blocks[action])
end
def base_metrics
{ :user_id => current_user.id, :shard => ActiveRecord::Shard.current }
end
module ClassMethods
def metric_blocks
@metric_blocks ||= Hash.new do |hash, action|
# default: return an empty hash
hash[action] = lambda { {} }
end
end
def log_metrics_for(*actions, &block)
actions.each do |action|
metric_blocks[action] = block
end
end
end
end
class MyController < ApplicationController
log_metrics_for :show, :edit do
# the block must return a hash
{ :widget_count => @widgets.size }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment