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 with its own DSL or adding methods to object.
See examples:
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
Usage examples
Instance, singleton, class, object
anchor Array do
before singleton :[] do |*args|
puts "About to create an Array containing #{args}"
end
after :push do |*args|
puts "Just pushed #{args} into Array #{self}"
end
end
@b = Array.new
anchor @b do
after :push do
puts "This is only after @b called"
end
end
@a = Array[1, 2, 3] # outputs "About to create an Array containing [1, 2, 3]"
@a.push(4, 5, 6) # outputs "Just pushed [4, 5, 6] into Array Array"
@b.push(1, 2, 3) # outputs "Just pushed [4, 5, 6] into Array Array" and "This is only after @b called"
Getting called method’s arguments and block
anchor Anchor::Hooks do # sets *anchor* on module *Anchor::Hooks*
before singleton :included do |*args, &block| # sets *hook* on singleton method called included
puts "Just anchored on #{args[0]} with #{block}"
end
end
# To understand fully, see also: https://github.com/tione/anchor/blob/master/lib/anchor/hooks.rb#L67
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
How to use 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 in Rails 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