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/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 ⇒ Try::Value, Try::Error
Returns self.
-
#value? ⇒ Boolean
(also: #success?)
Returns true for an instance of a Value monad.
Instance Attribute Details
#exception ⇒ Exception (readonly)
Returns Caught exception.
16 17 18 |
# File 'lib/dry/monads/try.rb', line 16 def exception @exception end |
Class Method Details
.[](*exceptions, &block) ⇒ Try::Value, Try::Error
Safely runs a block
68 69 70 71 72 |
# File 'lib/dry/monads/try.rb', line 68 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
47 48 49 50 51 52 53 54 55 |
# File 'lib/dry/monads/try.rb', line 47 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
28 29 30 31 32 |
# File 'lib/dry/monads/try.rb', line 28 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.
82 83 84 |
# File 'lib/dry/monads/try.rb', line 82 def error? is_a?(Error) end |
#to_monad ⇒ Try::Value, Try::Error
Returns self.
90 91 92 |
# File 'lib/dry/monads/try.rb', line 90 def to_monad self end |