Skip to content

Instantly share code, notes, and snippets.

@gcao
Last active December 11, 2015 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gcao/4614761 to your computer and use it in GitHub Desktop.
Save gcao/4614761 to your computer and use it in GitHub Desktop.
rvm use 1.9.3@perf_aspect --create
class ApplicationController
end
class Products < ApplicationController
# Action
def action
foo
bar
end
# Other methods
def foo
caculation = 5 * 4
end
def bar
caculation = 1 / 5
end
end
##############################
class Perf
def initialize
@results = []
end
def log(note)
@start = Time.now
@note = note
end
def write!
if @results.find {|h| h[:note] == @note } # Update :sec method exists in results
@results.select { |h| h["note"] == @note; h[":sec"] = (Time.now - @start).round(3) }
else # Add new Hash to results
@results << { :note => @note, :sec => (Time.now - @start).round(3) }
end
end
def results
content = "
PERFORMANCE STATISTICS!
"
@results.each do |r|
content += r[:note] + " " + r[:sec].to_s + "
"
end
content += "
"
#Rails.logger.info content
puts content
end
end
##############################
require 'aspector'
class PerfAspect < Aspector::Base
# Change log level to DEBUG or TRACE to see how the aspect works
#logger.level = Aspector::Logging::DEBUG
around options[:action_methods] do |proxy|
@perf ||= Perf.new
proxy.call
@perf.results
end
around options[:other_methods], :method_arg => true do |method, proxy, *args, &block|
@perf.log(method)
result = proxy.call *args, &block
@perf.write!
result
end
def self.apply_to target, action_methods, other_methods = nil
other_methods ||= target.instance_methods(false) - action_methods
apply(target, :action_methods => action_methods, :other_methods => other_methods)
end
end
PerfAspect.apply_to(Products, [:action])
##############################
Products.new.action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment