Skip to content

Commit

Permalink
Add monads extension
Browse files Browse the repository at this point in the history
  • Loading branch information
skryukov committed Sep 29, 2019
1 parent 0d12164 commit b68d52e
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/dry/types/extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@
Dry::Types.register_extension(:maybe) do
require 'dry/types/extensions/maybe'
end

Dry::Types.register_extension(:monads) do
require 'dry/types/extensions/monads'
end
29 changes: 29 additions & 0 deletions lib/dry/types/extensions/monads.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# frozen_string_literal: true

require 'dry/monads/result'

module Dry
module Types
# Monad extension for Result
#
# @api public
class Result
include Dry::Monads::Result::Mixin

# Turn result into a monad
#
# This makes result objects work with dry-monads (or anything with a compatible interface)
#
# @return [Dry::Monads::Success,Dry::Monads::Failure]
#
# @api public
def to_monad
if success?
Success(input)
else
Failure([error, input])
end
end
end
end
end
45 changes: 45 additions & 0 deletions spec/extensions/monads/result_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

RSpec.describe Dry::Types::Result do
before { Dry::Types.load_extensions(:monads) }

let(:type) { Dry::Types['strict.string'] }

let(:result) { type.try(input) }

context 'interface' do
let(:input) { {} }

it 'responds to #to_monad' do
expect(result).to respond_to(:to_monad)
end
end

context 'with valid input' do
let(:input) { 'Jane' }

describe '#to_monad' do
it 'wraps Result with Success' do
monad = result.to_monad

expect(monad).to be_a Dry::Monads::Result
expect(monad).to be_success
expect(monad.value!).to eq(result.input)
end
end
end

context 'with invalid input' do
let(:input) { nil }

describe '#to_monad' do
it 'wraps Result with Failure' do
monad = result.to_monad

expect(monad).to be_a Dry::Monads::Result
expect(monad).to be_failure
expect(monad.failure).to eq([result.error, result.input])
end
end
end
end

0 comments on commit b68d52e

Please sign in to comment.