Skip to content

Commit

Permalink
Return coerced values when constraints aren't met
Browse files Browse the repository at this point in the history
  • Loading branch information
flash-gordon committed Nov 4, 2017
1 parent 2af980b commit 1697dd1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
4 changes: 2 additions & 2 deletions lib/dry/types/array/member.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ def valid?(value)
def try(input, &block)
if input.is_a?(::Array)
result = call(input, :try)
output = result.map(&:input)

if result.all?(&:success?)
output = result.map(&:input)
success(output)
else
failure = failure(input, result.select(&:failure?))
failure = failure(output, result.select(&:failure?))
block ? yield(failure) : failure
end
else
Expand Down
7 changes: 3 additions & 4 deletions lib/dry/types/constrained/coercible.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
module Dry
module Types
class Constrained
include Type

class Coercible < Constrained
# @param [Object] input
# @param [#call,nil] block
# @yieldparam [Failure] failure
# @yieldreturn [Result]
# @return [Result,Logic::Result,nil]
# @return [Result,nil]
def try(input, &block)
result = type.try(input)

Expand All @@ -18,7 +16,8 @@ def try(input, &block)
if validation.success?
result
else
block ? yield(validation) : validation
failure = failure(result.input, validation)
block ? yield(failure) : failure
end
else
block ? yield(result) : result
Expand Down
4 changes: 4 additions & 0 deletions spec/dry/types/constrained_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,9 @@
it 'raises when a given constraint is violated' do
expect { type[%w(a b)] }.to raise_error(Dry::Types::ConstraintError)
end

it 'coerces values' do
expect(type.try(%i(foo aa)).input).to eql(%w(foo aa))
end
end
end

0 comments on commit 1697dd1

Please sign in to comment.