On
Dynamic callbacks for Ruby blocks.
Gem | Source | Documentation
Inspired by http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
Usage
Basic usage.
require 'on'
def tweet(message, &block)
callback = On.new(:success, :failure, &block)
callback.call :success
rescue => e
callback.call :failure, e.message
end
tweet "hello world" do |callback|
callback.on :success do
# handle success
end
callback.on :failure do |error_message|
# handle error message
end
end
Usage with proc
Syntatic sugar for creating an on
callback from Proc.
require 'on/proc'
def tweet(message, &block)
callback = block.on(:success, :failure)
callback.call :success
rescue => e
callback.call :failure, e.message
end
tweet "hello world" do |callback|
callback.on :success do
# handle success
end
callback.on :failure do |error_message|
# handle error message
end
end
Testing with On::TestHelper
require 'minitest/autorun'
require 'on'
require 'on/test_helper'
class SomeTest < MiniTest::Spec
include On::TestHelper
let(:recorder) { On::TestHelper::Recorder.new }
it "records everything" do
on = On.new(:success, :failure, &recorder)
on.call :success, :some, :args
assert_callback recorder, :success, :some, :args
end
it "calls nothing" do
on = On.new(:success, :failure, &recorder)
# nothing called
refute_callbacks recorder
end
it "records everything manually" do
on = On.new(:success, :failure) do |result|
recorder.record_block
recorder.record_callback(result, :success, :failure)
end
on.call :success, :some, :args
assert_callback recorder, :success, :some, :args
end
end
Installation
Add this line to your application's Gemfile:
gem 'on', '~> 1.0.0'
And then execute:
$ bundle
Or install it yourself as:
$ gem install on
Contributing
- Fork it
- 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 new Pull Request
Release
Follow these steps to release this gem:
# Bump version in
edit lib/on/version.rb
edit README.md
git commit -m "Release X.Y.Z"
rake release