Class: Dry::Monads::Try
- Inherits:
-
Object
- Object
- Dry::Monads::Try
- Defined in:
- lib/dry/monads/try.rb,
lib/dry/monads/maybe.rb,
lib/dry/monads/either.rb,
lib/dry/monads/result.rb
Overview
Represents a value which can be either success or a failure (an exception). Use it to wrap code that can raise exceptions.
Defined Under Namespace
Modules: Mixin Classes: Error, Value
Constant Summary collapse
- DEFAULT_EXCEPTIONS =
[StandardError].freeze
Instance Attribute Summary collapse
-
#exception ⇒ Exception
readonly
Caught exception.
Class Method Summary collapse
-
.[](*exceptions, &block) ⇒ Try::Value, Try::Error
Safely runs a block.
-
.pure(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) ⇒ Object
Wraps a value with Value.
- .run(exceptions, f) ⇒ Try::Value, Try::Error
Instance Method Summary collapse
-
#error? ⇒ Boolean
(also: #failure?)
Returns true for an instance of a Error monad.
-
#to_monad ⇒ Maybe::Some, Maybe::None
Returns self.
-
#value? ⇒ Boolean
(also: #success?)
Returns true for an instance of a Value monad.
Instance Attribute Details
#exception ⇒ Exception (readonly)
Returns Caught exception.
20 21 22 |
# File 'lib/dry/monads/try.rb', line 20 def exception @exception end |
Class Method Details
.[](*exceptions, &block) ⇒ Try::Value, Try::Error
Safely runs a block
72 73 74 75 |
# File 'lib/dry/monads/try.rb', line 72 def [](*exceptions, &block) raise ArgumentError, 'At least one exception type required' if exceptions.empty? run(exceptions, block) end |
.pure(value, exceptions = DEFAULT_EXCEPTIONS) ⇒ Try::Value .pure(exceptions = DEFAULT_EXCEPTIONS, &block) ⇒ Try::Value
Wraps a value with Value
51 52 53 54 55 56 57 58 59 |
# File 'lib/dry/monads/try.rb', line 51 def pure(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) if value.equal?(Undefined) Value.new(DEFAULT_EXCEPTIONS, block) elsif block.nil? Value.new(exceptions, value) else Value.new(value, block) end end |
.run(exceptions, f) ⇒ Try::Value, Try::Error
32 33 34 35 36 |
# File 'lib/dry/monads/try.rb', line 32 def run(exceptions, f) Value.new(exceptions, f.call) rescue *exceptions => e Error.new(e) end |
Instance Method Details
#error? ⇒ Boolean Also known as: failure?
Returns true for an instance of a Error monad.
85 86 87 |
# File 'lib/dry/monads/try.rb', line 85 def error? is_a?(Error) end |
#to_monad ⇒ Maybe::Some, Maybe::None
Returns self.
93 94 95 |
# File 'lib/dry/monads/try.rb', line 93 def to_monad self end |