On <img src=“https://secure.travis-ci.org/neopoly/on.png?branch=master” alt=“Build Status” />
Dynamic callbacks for Ruby blocks.
Gem | Source | Documentation
Inspired by www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
Usage
Basic usage.
require 'on'
def tweet(, &block)
callback = On.new(:success, :failure, &block)
callback.call :success
rescue => e
callback.call :failure, e.
end
tweet "hello world" do |callback|
callback.on :success do
# handle success
end
callback.on :failure do ||
# handle error message
end
end
Usage with proc
Syntatic sugar for creating an on
callback from Proc.
require 'on/proc'
def tweet(, &block)
callback = block.on(:success, :failure)
callback.call :success
rescue => e
callback.call :failure, e.
end
tweet "hello world" do |callback|
callback.on :success do
# handle success
end
callback.on :failure do ||
# 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'
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