Skip to content

Commit

Permalink
Add when alias
Browse files Browse the repository at this point in the history
  • Loading branch information
jsuchal committed May 2, 2014
1 parent 97087b2 commit ebe3c88
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 8 deletions.
8 changes: 2 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ bus = Bus.new([
class DonationsController # < ActionController::Base
def create
listener = bus.
on(:donation_created) {|donation| send_user_to_payment_gateway(donation) }.
on(:donation_created) {|donation| send_user_to_payment_gateway(donation) }. # NOTE the dot!
on(:donation_invalid) {|donation| render donation.errors, status: :bad_request }

# or
Expand All @@ -46,7 +46,7 @@ class DonationsController # < ActionController::Base

# or

DonationService.new.add_donation(current_user, params[:donation], bus.on(
DonationService.new.add_donation(current_user, params[:donation], bus.when(
donation_created: ->(donation) { send_user_to_payment_gateway(donation) },
donation_invalid: ->(donation) { render donation.errors, status: :bad_request }
))
Expand All @@ -61,10 +61,6 @@ end

# service
class DonationService
def initialize(options={})
@donation_class = options.fetch(:donation_class) { Donation }
end

def add_donation(donor, donation_attributes, listener)
donation = donor.donations.build(donation_attributes)
if donation.save
Expand Down
2 changes: 2 additions & 0 deletions lib/bus.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ def on(event_or_hash, &block)
self.class.new(@listeners + listeners)
end

alias :when :on

def method_missing(method_name, *args)
responded = false
@listeners.each do |listener|
Expand Down
2 changes: 1 addition & 1 deletion lib/bus/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
class Bus
VERSION = '0.0.2'
VERSION = '0.0.3'
end
10 changes: 9 additions & 1 deletion spec/bus_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
let (:listener) { double }

it 'calls attached listener' do
bus = described_class.new.attach(listener)
bus = subject.attach(listener)

expect(listener).to receive(:event_fired)

Expand Down Expand Up @@ -58,6 +58,14 @@
bus.event_fired(:args)
end

it 'aliases on and when methods' do
bus = subject.when(:event_fired) {|args| listener.call(args)} # event_fired { do stuff }

expect(listener).to receive(:call).with(:args)

bus.event_fired(:args)
end

it 'throws an exception when no listener responds' do
expect { subject.event_fired }.to raise_error(Bus::NoListenerRespondedError, 'No listener responded to message \'event_fired\'')
end
Expand Down

0 comments on commit ebe3c88

Please sign in to comment.