Purpose
I love the concepts of AOP, but I did not like different too bloated libraries, so I made my own.
Anchor contains 91 lines of code and supports before, after and around.
See example: github.com/tione/anchor/tree/master/lib/anchor/support/rails.rb
Installation
Add to your Gemfile:
gem 'anchor' # add this row after "gem 'rails'" if rails is used
And run:
bundle install
Or run:
gem install anchor
Naming recommendations
You can name things as you want, but it is recommended to it so:
Example: Using anchor for models in Rails app
Create app/anchors/your_model_anchor.rb (For autoload file’s postfix has to be “_anchor.rb”)
anchor YourModel do
before :save do
puts "Before save #{self.inspect}"
end
end
Example: Using anchor in models
You can also do in app/models/your_model.rb
class YourModel
include Anchor::Hooks
before :save do
puts "Before save #{self.inspect}"
end
end
Usage examples
Instance, singleton, class, object
class Example
def self.class_method
"CLASS_METHOD"
end
def instance_method
"INSTANCE_METHOD"
end
end
anchor Example do
before singleton :class_method do
puts "before class_method"
end
after :instance_method do
puts "after instance_method"
end
end
@example = Example.new
@other = Example.new
anchor @example do
before :instance_method do
puts "before @example
end
end
Method regexp
anchor Yourmodel do
before self.instance_methods.grep(/$methods/) do
puts
end
end
You can find some examples from:
TODO: add some examples more