Last active
December 11, 2015 14:29
-
-
Save gcao/4614761 to your computer and use it in GitHub Desktop.
Use Aspector for stackoverflow question
http://stackoverflow.com/questions/14396035/ruby-rails-prepend-append-code-to-all-methods
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
rvm use 1.9.3@perf_aspect --create |
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 | |
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