Skip to content

Commit

Permalink
Implement #method_missing for each monad
Browse files Browse the repository at this point in the history
  • Loading branch information
tomstuart committed Aug 2, 2014
1 parent f424379 commit 2a9426c
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/monads/monad.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ def within(&block)
end
end

def method_missing(*args, &block)
within do |value|
value.public_send(*args, &block)
end
end

private

def ensure_monadic_result(&block)
Expand Down
20 changes: 20 additions & 0 deletions spec/monads/eventually_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,25 @@ module Monads
end
end
end

describe 'handling unrecognised messages' do
let(:value) { double }
let(:response) { double }

before(:example) do
allow(value).to receive(:challenge).and_return(response)
end

it 'forwards any unrecognised message to the block’s value' do
expect(value).to receive(:challenge)
Eventually.new { |success| success.call(value) }.challenge.run {}
end

it 'returns the message’s result wrapped in an Eventually' do
@result = nil
Eventually.new { |success| success.call(value) }.challenge.run { |result| @result = result }
expect(@result).to eq response
end
end
end
end
22 changes: 22 additions & 0 deletions spec/monads/many_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,27 @@ module Monads
end
end
end

describe 'handling unrecognised messages' do
let(:values) { [double, double, double] }
let(:responses) { [double, double, double] }

before(:example) do
values.zip(responses) do |value, response|
allow(value).to receive(:challenge).and_return(response)
end
end

it 'forwards any unrecognised message to each value' do
values.each do |value|
expect(value).to receive(:challenge)
end
many.challenge
end

it 'returns the messages’ results wrapped in a Many' do
expect(many.challenge.values).to eq responses
end
end
end
end
17 changes: 17 additions & 0 deletions spec/monads/optional_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,22 @@ module Monads
end
end
end

describe 'handling unrecognised messages' do
let(:response) { double }

before(:example) do
allow(value).to receive(:challenge).and_return(response)
end

it 'forwards any unrecognised message to the value' do
expect(value).to receive(:challenge)
optional.challenge
end

it 'returns the message’s result wrapped in an Optional' do
expect(optional.challenge.value).to eq response
end
end
end
end

0 comments on commit 2a9426c

Please sign in to comment.