Callbacks
Callbacks is a simple shard that lets you write callbacks to be run before, after or around a specific method.
Installation
Add this to your application's shard.yml
:
dependencies:
callbacks:
github: hugoabonizio/callbacks.cr
Usage
The following example shows a basic usage of Callbacks
module.
require "callbacks"
class MyModel
include Callbacks
before :save do
log "Saving model..."
call_a_method
# ...
end
after :find, id : Int do
proccess_the_result
# ...
end
end
Keep the original value
Even after defining a callback to run after or around a method, the original returned value will be maintained.
class MyModel
include Callbacks
def calculate
123
end
after :calculate do
# ...
end
end
MyModel.new.calculate # => 123
Cancel the execution
If the before callback returns false, the original method will not be called. This prevent the method chain to continue (helpful to avoid saving a model if there are some errors).
class MyModel
include Callbacks
def calculate
123
end
before :calculate do
1 == 2
end
end
MyModel.new.calculate # => nil
Contributing
- Fork it ( https://github.com/hugoabonizio/callbacks.cr/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
Contributors
- hugoabonizio Hugo Abonizio - creator, maintainer