Created
November 15, 2011 22:22
-
-
Save myronmarston/1368573 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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