Usage
Methods you should be using
Although Aspekt consists of 4 classes and 2 modules, you should be using directly only 3 methods which API will never change:
- #before (Aspekt::Helpers::ShorthandMethods#before)
- #after (Aspekt::Helpers::ShorthandMethods#after)
- #around (Aspekt::Helpers::ShorthandMethods#around)
before|after|around ([instance(s)|type(s): Symbol|Regexp|Object|Array<Symbol|Regexp|Object>],) method(s): Symbol|Regexp|Array<Symbol|Regexp> do |joinpoint|
# what to do ...
# in case of around, `joinpoint.proceed` has to be called
end
- If instance or type is not specified, type: self is assumed.
- If you want, you can overwrite them and use them in your application as you want... Or you just create around advice for them and change arguments order as you like.
Example #1: In class body
class Example
def one; end
def two; end
def self.three; end
def self.four; end
before method: :one do
puts "before method one"
end
after({type: self, methods: [:one, :two]}, {instance: self, method: :three}) do |joinpoint|
puts "method #{joinpoint[:method]} was called on #{self} with arguments #{joinpoint[:args]}"
end
around instance: self, method: /thr/ do |joinpoint|
puts "Before around #{joinpoint}"
result = joinpoint.proceed # calling orginal method
puts "After around #{joinpoint}"
result # return orginal value
end
class<<self
before method: :four do
puts "before four"
end
end
end
Example #2: In random place
before types: [/Strin/, /Arra/], instances: [some_object, :SomeClassForSingletonMethods], methods: [/^beginning_with/, :to_mushroom] do |joinpoint|
puts joinpoint
end
Example #3: In aspects
Recommended
- Create folder called 'aspects' in your load path.
- Create Aspect for Concern:
# ./aspects/logging/exceptions.rb (parent folder of 'aspects' must be in load path):
module Aspects
module Logging
module Exceptions
after type: Exception, method: :initialize do |joinpoint|
MyLogger.log "Just threw exception #{self.class}: #{self.backtrace}"
end
end
end
end
You could also
- Create your own logic, but you should take care, that aspects are loaded.
Installation
Using Bundler
Add to your Gemfile:
gem 'aspekt'
And run:
bundle install
Using gem
gem install aspekt