Skip to content

Instantly share code, notes, and snippets.

@rjnienaber
Last active December 21, 2015 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjnienaber/6261875 to your computer and use it in GitHub Desktop.
Save rjnienaber/6261875 to your computer and use it in GitHub Desktop.
An example of AOP in Ruby using aspector (includes benchmark)
require 'aspector'
require 'benchmark'
ITERATIONS = 100_000
class MyProcessor
def test_one
1 + 1
end
end
class MySecondProcessor
def test_two
sleep 3
puts "I've awoken!"
end
end
Benchmark.bmbm do |bm|
bm.report('baseline') do
ITERATIONS.times { MyProcessor.new.test_one }
end
end
#Example results
# user system total real
#baseline 0.110000 0.000000 0.110000 ( 0.061000)
class EmptyAspect < Aspector::Base
target do
def do_this proxy, &block
proxy.call &block
end
end
around options[:method], :do_this
end
class TimingAspect < Aspector::Base
target do
def do_this proxy, &block
start = Time.now
begin
proxy.call &block
ensure
puts "Time taken: #{Time.now - start}"
end
end
end
around options[:method], :do_this
end
##############################
EmptyAspect.apply MyProcessor, :method => :test_one
puts ""
Benchmark.bmbm do |bm|
bm.report('with AOP') do
ITERATIONS.times { MyProcessor.new.test_one }
end
end
#Example results
# user system total real
#with AOP 0.180000 0.000000 0.180000 ( 0.136000)
#
# Overhead is about 0.75 microseconds per method call
TimingAspect.apply MySecondProcessor, :method => :test_two
MySecondProcessor.new.test_two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment