### Simple type constraint examples Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Examples of using simple type constraints with Result monads. ```ruby # Example with simple constraint class UserService include Dry::Monads::Result(Symbol) # Only symbols allowed as errors end UserService::Failure(:not_found) # OK (Symbol matches) UserService::Failure("string") # => InvalidFailureTypeError (String doesn't match) UserService::Failure(42) # => InvalidFailureTypeError (Integer doesn't match) ``` -------------------------------- ### Document Usage Patterns Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/README.md Standard format for documenting usage examples while excluding test-specific code. ```ruby # ✓ Usage example Success(42).fmap { |x| x * 2 } # => Success(84) # ✗ Test code (not included) expect(Success(42)).to eq(Success(42)) ``` -------------------------------- ### Nesting Level Mapping Examples Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Demonstrates how to handle 4-level nesting by chaining fmap operations. ```ruby # 4-level nesting Success(List[Some(Failure(:e))]).fmap2 { |maybe| maybe.fmap { |failure| ... } } # Or chain fmap and fmap3: success_list_maybe_failure .fmap { |list| list.fmap3 { |failure| ... } } ``` -------------------------------- ### Handling ConstructorNotAppliedError Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Example of rescuing the error and accessing the descriptive message. ```ruby begin value = None.value! rescue Dry::Monads::ConstructorNotAppliedError => e puts e.message # => "For calling .value! on None() build a value by appending parens: None()" end # Correct value = None().value! # => UnwrapError (expected - None has no value) ``` -------------------------------- ### Sequential Operations with Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Example of chaining multiple monadic operations sequentially within a single method. ```ruby def create_user_with_profile user_data = yield validate_user(params) user = yield save_user(user_data) profile_data = yield validate_profile(params) profile = yield create_profile(user, profile_data) send_welcome_email(user) Success({ user: user, profile: profile }) end ``` -------------------------------- ### Example of a side-effect function returning Unit Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/types.md A practical example of a method that performs a side effect and returns a successful Unit result. ```ruby def side_effect_only puts "Doing something" Success(Unit) end ``` -------------------------------- ### Handling UnwrapError Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Example of rescuing UnwrapError and accessing the receiver attribute. ```ruby begin Failure(:database_error).value! rescue Dry::Monads::UnwrapError => e puts e.receiver.inspect # => Failure(:database_error) puts e.message # => "value! was called on Failure(:database_error)" end ``` -------------------------------- ### Success[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Shortcut constructor for multiple values as array. ```APIDOC ## Success[] ### Description Shortcut constructor for multiple values as array. ### Parameters - **value** (splat) - Required - Values to wrap as array ### Returns Success([*values]) ### Example ```ruby Success[200, {}, ['ok']] # => Success([200, {}, ['ok']]) ``` ``` -------------------------------- ### Create a Task instance Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Initialize a Task by wrapping a block for asynchronous execution or by wrapping an existing concurrent-ruby Promise. ```ruby Task.new { sleep 1; 42 } # Creates task executing block Task.new(promise) # Wraps existing promise ``` -------------------------------- ### Enable Do Notation for Methods Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Shows how to include the Do module and apply it to specific methods within a service class. ```ruby require 'dry/monads/all' class UserService include Dry::Monads[:result, :do] include Dry::Monads::Do.for(:create_user) def create_user(params) user_data = yield validate(params) user = yield save_user(user_data) Success(user) end end ``` -------------------------------- ### Handling InvalidFailureTypeError Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Example of rescuing InvalidFailureTypeError and accessing the error message. ```ruby require 'dry/monads/all' class PaymentService ErrorType = ->(val) { val.is_a?(Symbol) && val.in?([:insufficient_funds, :invalid_card]) } include Dry::Monads::Result(ErrorType) end begin PaymentService::Failure(:insufficient_funds) # OK rescue Dry::Monads::InvalidFailureTypeError # Won't happen end begin PaymentService::Failure(:unknown_error) rescue Dry::Monads::InvalidFailureTypeError => e puts e.message # => "Cannot create Failure from :unknown_error, it doesn't meet the constraints" end ``` -------------------------------- ### List[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Shortcut constructor for creating a list from multiple values. ```APIDOC ## List[] ### Description Shortcut constructor for creating a list from multiple values. ### Parameters - **values** (splat) - Required - Elements to include ### Returns - **List** - A new List instance ### Example List[1, 2, 3] # => List[1, 2, 3] ``` -------------------------------- ### Compare Monadic Chaining and Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Demonstrates the difference between manual bind chaining and the cleaner imperative syntax enabled by Do notation. ```ruby # Without Do notation def fetch_data get_user.bind { |user| get_profile(user).bind { |profile| Success({ user: user, profile: profile }) } } end # With Do notation include Dry::Monads::Do.for(:fetch_data) def fetch_data user = yield get_user profile = yield get_profile(user) Success({ user: user, profile: profile }) end ``` -------------------------------- ### Basic Import and Result Usage Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/index.md Demonstrates including the Result and Do modules to return Success or Failure objects from a service method. ```ruby require 'dry/monads/all' class UserService include Dry::Monads[:result, :do] def create_user(name) if name.empty? Failure(:name_empty) else Success({ id: 1, name: name }) end end end ``` -------------------------------- ### Nested Data Validation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Example of using fmap2 to transform deeply nested results within a class. ```ruby class Validator include Dry::Monads[:result, :maybe] def validate_nested_data(data) # Transforms deeply nested valid results Success(data) .fmap2 { |inner| process(inner) } .fmap2 { |processed| transform(processed) } end end ``` -------------------------------- ### Get Maybe Monad Warning Setting Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Retrieves the current boolean state of the implicit nil coercion warning setting. ```ruby Dry::Monads::Maybe.warn_on_implicit_nil_coercion # => true ``` -------------------------------- ### Construct a Some instance with multiple values Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md A shortcut constructor that wraps multiple arguments into an array. ```ruby Some[200, {}, ['ok']] # => Some([200, {}, ['ok']]) ``` -------------------------------- ### Apply Do.for with visibility control Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Demonstrates applying do-notation to methods while maintaining their original public, private, or protected visibility. ```ruby class Service include Dry::Monads[:result, :do] include Dry::Monads::Do.for(:public_flow, :private_flow) def public_flow # Public method with do-notation end private def private_flow # Private method with do-notation end end ``` -------------------------------- ### Get string representation of a Lazy instance Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/lazy.md Returns a string indicating the state of the computation, including whether it is evaluated or contains an error. ```ruby Lazy { 42 }.to_s # => "Lazy(?)" Lazy { 42 }.force.to_s # => "Lazy(42)" ``` -------------------------------- ### Create a Task Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Initializes a new Task from a block to be executed asynchronously. ```ruby Task(&block) ``` ```ruby include Dry::Monads[:task] task = Task { sleep 1; 42 } ``` -------------------------------- ### to_monad Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/validated.md Returns the instance itself. ```APIDOC ## to_monad ### Description Returns the instance itself. ### Returns - **self** - The current instance ``` -------------------------------- ### Some[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md A shortcut constructor for wrapping multiple values as an array within a Some instance. ```APIDOC ## Some[*value] ### Description Shortcut constructor for multiple values as array. ### Parameters - **value** (splat) - Required - Values to wrap as array ### Returns Some([*values]) ### Example ```ruby Some[200, {}, ['ok']] # => Some([200, {}, ['ok']]) ``` ``` -------------------------------- ### Create a List with List[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Use the splat constructor to initialize a list from multiple values. ```ruby List[1, 2, 3] # => List[1, 2, 3] List[] # => List[] ``` -------------------------------- ### Project File Structure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/REFERENCE.md Visual representation of the library's directory layout and core components. ```text lib/ ├── dry-monads.rb # Entry point └── dry/monads/ ├── version.rb # VERSION constant ├── constants.rb # Core constants ├── errors.rb # Error classes ├── registry.rb # Monad registry ├── extensions.rb # Extension loader ├── extensions/ │ ├── pretty_print.rb │ ├── rspec.rb │ └── super_diff.rb ├── result.rb # Result monad ├── result/fixed.rb # Type-constrained Result ├── maybe.rb # Maybe monad ├── try.rb # Try monad ├── list.rb # List monad ├── task.rb # Task monad ├── lazy.rb # Lazy monad ├── validated.rb # Validated monad ├── do.rb # Do notation ├── right_biased.rb # RightBiased interface ├── transformer.rb # Nested transformations ├── traverse.rb # List traversal ├── unit.rb # Unit constant ├── curry.rb # Currying support ├── conversion_stubs.rb # Conversion fallbacks └── all.rb # Loads all monads ``` -------------------------------- ### Constructing None instances Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Returns a singleton-like None instance. ```ruby None() # => None() ``` -------------------------------- ### Construct Success with array Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Shortcut constructor to wrap multiple values into a single array within a Success. ```ruby Success[200, {}, ['ok']] # => Success([200, {}, ['ok']]) ``` -------------------------------- ### Implement Do notation in a service class Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Demonstrates wrapping a method with Do notation to auto-unwrap monadic results using yield. ```ruby require 'dry/monads/all' class OrderService include Dry::Monads[:result, :maybe, :do] include Dry::Monads::Do.for(:place_order) def initialize(repo) @repo = repo end def place_order(user_id, items) # Do notation auto-unwraps each yield user = yield fetch_user(user_id) validated_items = yield validate_items(items) order = yield create_order(user, validated_items) yield notify_user(user, order) Success(order) end private def fetch_user(id) @repo.find_user(id) .some? ? Success(@repo.find_user(id).value!) : Failure(:user_not_found) end def validate_items(items) items.empty? ? Failure(:no_items) : Success(items) end def create_order(user, items) Success(@repo.create_order(user, items)) end def notify_user(user, order) Success(Mailer.send_order_confirmation(user, order)) end end # Usage service = OrderService.new(repo) result = service.place_order(123, [item1, item2]) result.either( ->(order) { puts "Order placed: #{order.id}" }, ->(error) { puts "Error: #{error}" } ) ``` -------------------------------- ### Rescue specific exceptions with Try Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Demonstrates wrapping an operation in Try and using fmap and recover to handle potential errors. ```ruby require 'dry/monads/all' include Dry::Monads::Try::Mixin result = Try(ZeroDivisionError) { 10 / 2 } result .fmap { |x| x * 2 } .recover(ZeroDivisionError) { |e| "Error: #{e.message}" } .value # => 20 ``` -------------------------------- ### Task.new Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Creates a new Task instance, either by wrapping an existing concurrent-ruby Promise or by executing a provided block asynchronously. ```APIDOC ## Task.new ### Description Creates a Task, either wrapping an existing promise or executing a block. ### Parameters - **promise** (Promise) - Optional - Existing concurrent-ruby Promise - **block** (Proc) - Optional - Block to execute asynchronously ### Returns - **Task** - The created task instance ``` -------------------------------- ### Applying Monads Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/right-biased.md Short-circuits the application process for failure cases. ```ruby Failure(:e).apply(Success(5)) # => Failure(:e) ``` -------------------------------- ### Maybe::None#eql?, Maybe::None#== Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Checks equality for the None singleton. ```APIDOC ## Maybe::None#eql? / Maybe::None#== ### Description None is singleton, all None instances are equal. ### Returns Boolean ``` -------------------------------- ### Define Method Signature Format Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/README.md Standard Ruby syntax for documenting method signatures. ```ruby method_name(param1, param2 = default, &block) ``` -------------------------------- ### Implement Service Object with Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Uses Do notation to chain validation, database persistence, and email notification steps within a service object. ```ruby class CreateUserService include Dry::Monads[:result, :try, :do] include Dry::Monads::Do.for(:call) def initialize(user_repo, mailer) @user_repo = user_repo @mailer = mailer end def call(params) validated = yield validate_params(params) user = yield create_user(validated) yield send_email(user) Success(user) end private def validate_params(params) UserSchema.call(params).to_monad end def create_user(data) Try(Database::Error) { @user_repo.create(data) }.to_result end def send_email(user) Try(Mailer::Error) { @mailer.send(user.email) }.to_result end end ``` -------------------------------- ### Implement Nested Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Shows how to enable Do notation for multiple methods within the same class to allow nested monadic chaining. ```ruby include Dry::Monads[:result, :do] include Dry::Monads::Do.for(:outer, :inner) def outer val = yield inner Success(val * 2) end def inner Success(21) end outer # => Success(42) ``` -------------------------------- ### Structural Transformation Limitations Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Illustrates when to avoid fmap2 for structural changes and provides the correct alternative approach. ```ruby # WRONG - trying to structure-change with fmap2 list = List[Some(1), Some(2)] list.fmap2 { |x| None() } # Results in List[Some(None()), Some(None())] # CORRECT - use explicit transformation list.fmap { |maybe| maybe.maybe { Some(nil) } } # Or flatten: list.fmap { |maybe| maybe.fmap { |x| None() }.flatten } ``` -------------------------------- ### Loading Extensions Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Loads optional extensions such as pretty_print or RSpec matchers. ```ruby Dry::Monads.load_extensions(:pretty_print) ``` -------------------------------- ### Instance Predicates (none?, some?, failure?, success?) Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Methods to check the presence of a value within a Maybe instance. ```APIDOC ## Instance Predicates ### Description Predicates to check value presence. `failure?` and `success?` are aliases for `none?` and `some?` respectively. ### Methods - **none?()** - Returns true if value is absent. - **some?()** - Returns true if value is present. - **failure?()** - Alias for none?. - **success?()** - Alias for some?. ### Returns - **Boolean** ### Example ```ruby Some(42).some? # => true None().none? # => true ``` ``` -------------------------------- ### None() Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Constructs a None instance. ```APIDOC ## None() ### Description Constructs a None instance (all None instances are identical). ### Returns `Maybe::None` (singleton-like) ### Example ```ruby None() # => None() ``` ``` -------------------------------- ### Listing Known Monads Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Displays the registry of all available monads and their corresponding modules. ```ruby { do: "Do::All", lazy: "Lazy", list: "List", maybe: "Maybe", task: "Task", try: "Try", validated: "Validated", result: ["Result", "Result::Fixed"] } ``` -------------------------------- ### Define Parameter Table Format Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/README.md Standard Markdown table structure for documenting method parameters. ```markdown | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | name | String | — | Parameter description | ``` -------------------------------- ### Constructing Valid instances Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/validated.md Creates a Valid instance using either a direct value or a block. ```ruby Valid(42) # => Valid(42) Valid { 42 } # => Valid(42) ``` -------------------------------- ### Load All Monads Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Require all available monad classes at once. ```ruby require 'dry/monads/all' ``` -------------------------------- ### Successful value! and fallback usage Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Shows cases where value! does not raise an error and how fallback methods prevent exceptions. ```ruby Success(42).value! # => 42 (no error) Failure(:error).value_or(0) # => 0 (no error) ``` -------------------------------- ### Transform with Callable Arguments Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Demonstrates passing callable objects (procs) to fmap2 and fmap3 for transformations. ```ruby add_ten = -> x { x + 10 } double = -> x { x * 2 } Success(Some(5)).fmap2(add_ten) # => Success(Some(15)) List[Success(1), Success(2)].fmap2(double) # => List[Success(2), Success(4)] Success(List[Some(1)]).fmap3(add_ten) # => Success(List[Some(11)]) ``` -------------------------------- ### Workaround for Validated bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Shows the correct usage of apply and fmap as alternatives to bind for Validated objects. ```ruby Valid { |x| x * 2 }.apply(Valid(5)) # => Valid(10) Valid(5).fmap { |x| x * 2 } # => Valid(10) ``` -------------------------------- ### Selective Monad Mixin Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/index.md Demonstrates using the registry to include specific monads into a class. ```ruby class Service include Dry::Monads[:result, :maybe, :do] # Provides Result, Maybe, and Do-notation constructors end ``` -------------------------------- ### View module hierarchy Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/REFERENCE.md Visual representation of the dry-monads namespace structure. ```text Dry::Monads (main namespace) ├── Monads (actual module) ├── Result │ ├── Success (RightBiased::Right) │ ├── Failure (RightBiased::Left) │ ├── Fixed (type-constrained variant) │ └── Mixin ├── Maybe │ ├── Some (RightBiased::Right) │ ├── None (RightBiased::Left) │ ├── Hash (utilities) │ └── Mixin ├── Try │ ├── Value (RightBiased::Right) │ ├── Error (RightBiased::Left) │ └── Mixin ├── List │ ├── ListBuilder (typed variants) │ └── Mixin ├── Task │ └── Mixin ├── Lazy (extends Task) │ └── Mixin ├── Validated │ ├── Valid (applicative right) │ ├── Invalid (applicative left) │ └── Mixin ├── Do │ ├── Halt (internal) │ ├── MethodTracker (internal) │ └── All (full mixin) ├── RightBiased │ ├── Right │ └── Left ├── Transformer ├── Registry (module) └── Constants (module) ``` -------------------------------- ### Define Failure[] constructor Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Shortcut constructor that wraps multiple values into an array. ```ruby Failure[*value] ``` ```ruby Failure[:error, :not_found] # => Failure([:error, :not_found]) ``` -------------------------------- ### Constructing Some instances Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Wraps a value or block result into a Some instance. Raises an ArgumentError if the provided value is nil. ```ruby Some(42) # => Some(42) Some { 42 } # => Some(42) Some(nil) # => ArgumentError: nil cannot be some ``` -------------------------------- ### Maybe::None equality check Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Demonstrates that all None instances are equal. ```ruby None() == None() # => true ``` -------------------------------- ### Use alternative operator | Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/right-biased.md Returns the current instance for Right, ignoring the provided alternative. ```ruby Success(5) | Failure(:fallback) # => Success(5) ``` -------------------------------- ### Execute code with exception handling using Try.run Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Invokes a callable and rescues specified exceptions, returning a Try::Value or Try::Error. ```ruby Try.run([ZeroDivisionError], -> { 10 / 2 }) # => Try::Value(5) Try.run([ZeroDivisionError], -> { 10 / 0 }) # => Try::Error(ZeroDivisionError) ``` -------------------------------- ### Error Handling with Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Demonstrates how failures propagate through the method and can be handled externally. ```ruby def risky_operation data = yield fetch_data validated = yield validate(data) Success(process(validated)) end # If any operation returns Failure, the whole thing returns that Failure risky_operation.or { |error| handle_error(error) } ``` -------------------------------- ### Instantiating ConstructorNotAppliedError Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Shows the constructor signature for the error class. ```ruby ConstructorNotAppliedError.new(method_name, constructor_name) ``` -------------------------------- ### Failure[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Shortcut constructor for creating a Failure containing an array of values. ```APIDOC ## Failure[*value] ### Description Shortcut constructor for multiple values as array. ### Parameters - **value** (splat) - Required - Values to wrap as array ### Returns - **Failure** - Failure containing an array of values ``` -------------------------------- ### Define bind method signature Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Short-circuits the operation and returns the instance unchanged. ```ruby bind(*args, &block) ``` -------------------------------- ### Wrap values with Result.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Creates a Success instance from a direct value or a block. ```ruby Result.pure(42) # => Success(42) Result.pure { 42 } # => Success(42) ``` -------------------------------- ### Create Pipeline with Error Collection Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Demonstrates a sequential pipeline where any failure short-circuits the execution, allowing for error handling via the or method. ```ruby include Dry::Monads[:result, :do] include Dry::Monads::Do.for(:process_pipeline) def process_pipeline(input) step1 = yield transform_step1(input) step2 = yield transform_step2(step1) step3 = yield transform_step3(step2) Success(step3) end # Any Failure short-circuits and returns immediately result = process_pipeline(data) result.or { |err| puts "Failed at: #{err}" } ``` -------------------------------- ### Fallback with or Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Provides a fallback value or executes a block when an error occurs. ```ruby Try[ZeroDivisionError] { 10 / 0 }.or { "division failed" } # => "division failed" Try[ZeroDivisionError] { 10 / 0 }.or { |err| err.message } # => "divided by 0" ``` -------------------------------- ### Task.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Returns an immediately-fulfilled Task containing the provided value or the result of the provided block. ```APIDOC ## Task.pure ### Description Returns immediately-fulfilled Task with given value. ### Parameters - **value** (Object) - Optional - Value to wrap - **block** (Proc) - Optional - Block to wrap (if value not given) ### Returns - **Task** - An already fulfilled task ``` -------------------------------- ### Load Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Explicitly require the Do module for specific methods. ```ruby include Dry::Monads::Do.for(:method_name) # Do module loaded if not already ``` -------------------------------- ### Task::Mixin[executor] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Creates a mixin with an injected executor for Task execution. ```APIDOC ## Task::Mixin[executor] ### Description Creates a mixin with injected executor, allowing tasks to run on a specific thread pool. ### Parameters - **executor** (Concurrent::AbstractExecutorService or Symbol) - Required - Executor to use ### Returns - **Module** - A mixin module configured with the provided executor ### Example ```ruby IO_POOL = Concurrent::ThreadPoolExecutor.new class Service include Dry::Monads::Task::Mixin[IO_POOL] def fetch_data Task { blocking_call } # Uses IO_POOL end end ``` ``` -------------------------------- ### Check value presence with predicates Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Use some? and none? to verify if the Maybe instance contains a value or is empty. ```ruby Some(42).some? # => true None().none? # => true ``` -------------------------------- ### Value(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Constructs a Try::Value instance. ```APIDOC ## Value(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) ### Description Constructs a Try::Value object wrapping the provided value or the result of the block. ### Parameters - **value** (Object) - Optional - Value to wrap. - **exceptions** (Array) - Optional - Exception types to catch. - **block** (Proc) - Optional - Block to wrap if value is not provided. ### Returns - **Try::Value** ``` -------------------------------- ### Result.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Wraps a value with Success. Accepts either a value or a block. ```APIDOC ## Result.pure ### Description Wraps a value with Success. Accepts either a value or a block. ### Parameters - **value** (Object) - Optional - Value to wrap, or block if omitted - **block** (Proc) - Optional - Block returning value (if value not given) ### Returns Result::Success ### Example ```ruby Result.pure(42) # => Success(42) Result.pure { 42 } # => Success(42) ``` ``` -------------------------------- ### Define failure? and success? predicate methods Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Checks the state of the result instance. ```ruby failure?() success?() ``` -------------------------------- ### Check Version Information Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Retrieve the current version of the dry-monads library. ```ruby Dry::Monads::VERSION # => "1.10.0" ``` -------------------------------- ### Create a rejected Task Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Return a Task that is already in a rejected state with the provided exception. ```ruby Task.failed(StandardError.new("failed")) ``` -------------------------------- ### Maybe::None#or usage Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Provides a fallback value or executes a block when the value is absent. ```ruby None().or('default') # => "default" None().or { Time.now } # => current time None().or('a', 'b') { |a, b| a + b } # => "ab" ``` -------------------------------- ### Conditional Logic in Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Shows that standard Ruby control flow structures like if/else work naturally alongside yield. ```ruby def conditional_flow user = yield fetch_user(id) if user.admin? profile = yield fetch_admin_profile(user) else profile = yield fetch_user_profile(user) end Success(profile) end ``` -------------------------------- ### bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Monadic bind (flatmap) where the block returns another Task. ```APIDOC ## bind ### Description Monadic bind (flatmap). Block returns another Task. ### Parameters - **block** (Proc) - Required - Block returning Task ### Returns Task ``` -------------------------------- ### Expensive Computation Deferral Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/lazy.md Demonstrates deferring a configuration load until the value is explicitly requested. ```ruby config = Lazy { load_configuration } # Later, in different parts of code if need_config? settings = config.value! end # Already computed, returns cached value other_settings = config.value! ``` -------------------------------- ### Generate a List with List.unfold Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Build a list iteratively using a block that returns Maybe values. ```ruby List.unfold(1) do |n| n <= 5 ? Some([n + 1, n * 2]) : None() end # => List[2, 4, 6, 8, 10] ``` -------------------------------- ### Importing dry-core Constants Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/types.md Commonly used frozen constants imported from dry-core. ```ruby EMPTY_ARRAY = [].freeze EMPTY_HASH = {}.freeze ``` -------------------------------- ### Apply functions with either Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Executes the success-case function when called on a Success instance. ```ruby Success(1).either(-> x { x + 1 }, -> x { x + 2 }) # => 2 ``` -------------------------------- ### Construct Success instances Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Creates a Success instance using either a direct value or a block. ```ruby Success(value = Undefined, &block) ``` ```ruby include Dry::Monads[:result] Success(42) # => Success(42) Success { 42 } # => Success(42) ``` -------------------------------- ### apply Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Applies a stored function to a given Task value using currying. ```APIDOC ## apply ### Description Applies stored function to given Task value. Uses currying. ### Parameters - **val** (Task) - Optional - Task to apply to - **block** (Proc) - Required - Task-returning block ### Returns Task ``` -------------------------------- ### Maybe::None#fmap, Maybe::None#maybe Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Short-circuits and returns self unchanged, allowing for method chaining. ```APIDOC ## Maybe::None#fmap / Maybe::None#maybe ### Description Short-circuits, returns self unchanged (method chaining). ### Returns self ``` -------------------------------- ### Task(&block) Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Creates a new Task from a block to be executed asynchronously. ```APIDOC ## Task(&block) ### Description Creates a new Task from a block. The block is executed asynchronously. ### Parameters - **block** (Proc) - Required - Block to execute asynchronously ### Returns - **Task** - A new Task instance ### Example ```ruby include Dry::Monads[:task] task = Task { sleep 1; 42 } ``` ``` -------------------------------- ### Success#bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Unwraps and applies a function to the value. Returns the result directly. ```APIDOC ## Success#bind ### Description Unwraps and applies a function to the value. Returns the result directly (no wrapping). ### Parameters - **args** (Array) - Required - Arguments passed to block or callable - **block** (Proc) - Required - Block or callable to apply ### Returns Result or other monad type ### Example ```ruby Success(4).bind { |x| Success(x + 1) } # => Success(5) Success(4).bind { |x| Failure(:error) } # => Failure(:error) ``` ``` -------------------------------- ### Maybe::None#or Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Yields to a block or returns the provided arguments as a fallback value. ```APIDOC ## Maybe::None#or ### Description Yields to a block or returns the first argument as a fallback value. ### Parameters - **args** (Array) - Optional - Fallback value or arguments to block - **block** (Proc) - Optional - Block to call for fallback ### Returns Block result or fallback value ``` -------------------------------- ### Wrap values or blocks using Try.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Wraps a value or a block into a Try::Value without performing exception handling. ```ruby Try.pure(42) # => Try::Value(42) Try.pure { 42 } # => Try::Value(42) Try.pure(42, [ZeroDivisionError]) # => Try::Value(42) ``` -------------------------------- ### Chain operations with bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Use bind to sequence operations that return Result objects. The chain stops at the first Failure encountered. ```ruby result = Success(user_data) .bind { |data| validate(data) } .bind { |data| save_to_db(data) } .bind { |user| send_email(user) } result.or { puts "Operation failed" } ``` -------------------------------- ### Trigger ArgumentError with Some Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Demonstrates that Some cannot be initialized with a nil value. ```ruby Some(42) # OK Some(nil) # => ArgumentError: nil cannot be some ``` -------------------------------- ### or Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Rescues an error with a block returning another Task for recovery. ```APIDOC ## or ### Description Rescues error with block returning another Task (error recovery). ### Parameters - **block** (Proc) - Required - Block returning replacement Task ### Returns Task ``` -------------------------------- ### Try.run Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Invokes a callable, catching specified exceptions and wrapping the result in a Try monad. ```APIDOC ## Try.run(exceptions, f) ### Description Invokes a callable, catching specified exceptions and wrapping the result in a Try monad. ### Parameters - **exceptions** (Array) - Required - Exception classes to rescue - **f** (#call) - Required - Callable to invoke ### Returns - **Try::Value** on success - **Try::Error** on exception ### Example Try.run([ZeroDivisionError], -> { 10 / 2 }) # => Try::Value(5) Try.run([ZeroDivisionError], -> { 10 / 0 }) # => Try::Error(ZeroDivisionError) ``` -------------------------------- ### Task.failed Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Returns an immediately-rejected Task containing the provided exception. ```APIDOC ## Task.failed ### Description Returns immediately-rejected Task with given exception. ### Parameters - **exc** (Exception) - Required - Exception to wrap ### Returns - **Task** - An already rejected task ``` -------------------------------- ### Wrap values with List.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Create a list containing a single element from a value or a block. ```ruby List.pure(42) # => List[42] List.pure { 42 } # => List[Proc] ``` -------------------------------- ### Task[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Creates a Task with an explicit executor from concurrent-ruby, allowing control over the thread pool used for execution. ```APIDOC ## Task[] ### Description Creates a Task with explicit executor from concurrent-ruby. ### Parameters - **executor** (Concurrent::AbstractExecutorService or Symbol) - Required - Executor instance or symbol (:fast, :io, :immediate) - **block** (Proc) - Required - Block to execute ### Returns - **Task** - The created task instance ``` -------------------------------- ### Basic Do Notation Pattern Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Standard implementation of a method using Do notation to handle monadic results. ```ruby include Dry::Monads[:result, :do] include Dry::Monads::Do.for(:process) def process value = yield operation_returning_monad # If operation returns Failure, process halts here # value contains unwrapped success Success(transformed(value)) end ``` -------------------------------- ### or(*args, &block) Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Yields the exception to a block or returns the provided fallback value. ```APIDOC ## or(*args, &block) ### Description Yields the exception to a block or returns the first argument as a fallback value. ### Parameters - **args** (Array) - Optional - Fallback value or arguments to block - **block** (Proc) - Optional - Block to call with exception ### Returns - (Object) - Block result or fallback value ``` -------------------------------- ### Aggregation and Queries Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Methods for folding/reducing the list and querying its state. ```APIDOC ## fold_left(initial, &block) / foldl / reduce ### Description Left fold (reduce from left to right). ### Parameters - **initial** (Object) - Required - Initial accumulator value - **block** (Proc) - Required - Block taking (accumulator, element) ### Returns - **Result of fold** ## fold_right(initial, &block) / foldr ### Description Right fold (reduce from right to left). ### Parameters - **initial** (Object) - Required - Initial accumulator value - **block** (Proc) - Required - Block taking (element, accumulator) ### Returns - **Result of fold** ## empty?() ### Description Checks if the list is empty. ### Returns - **Boolean** ## size() ### Description Returns the list size. ### Returns - **Integer** ## to_ary() / to_a() ### Description Converts to an array (returns internal value). ### Returns - **Array** ``` -------------------------------- ### bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Unwraps the value and applies a function, catching exceptions and returning a Try::Error if one occurs. ```APIDOC ## bind(*args, &block) ### Description Unwraps and applies a function. Catches exceptions and returns Try::Error. ### Parameters - **args** (Array) - Optional - Arguments passed to callable - **block** (Proc) - Optional - Block to apply ### Returns Result of callable, or Try::Error if exception raised ### Example ```ruby val = Try::Value.new([ZeroDivisionError], 10) val.bind { |n| n / 2 } # => 5 val.bind { |n| n / 0 } # => Try::Error(ZeroDivisionError) ``` ``` -------------------------------- ### Success#either Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Applies first function to value (success case). ```APIDOC ## Success#either ### Description Applies first function to value (success case). ### Parameters - **f** (#call) - Required - Function to apply on success - **_** (#call) - Required - Ignored (for Failure) ### Returns Result of calling f ### Example ```ruby Success(1).either(-> x { x + 1 }, -> x { x + 2 }) # => 2 ``` ``` -------------------------------- ### Execute blocks with exception handling using Try Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Wraps code execution in a Try monad, catching specified exceptions or StandardError by default. ```ruby include Dry::Monads::Try::Mixin result = Try(ZeroDivisionError) { 10 / 2 } # => Try::Value(5) Try(ZeroDivisionError, TypeError) { 10 / 0 } # => Try::Error Try { 1 / 0 } # => Try::Error (catches StandardError) ``` -------------------------------- ### List.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/list.md Wraps a value or block in a list with a single element. ```APIDOC ## List.pure ### Description Wraps a value (or block) in a list with single element. ### Parameters - **value** (Object) - Optional - Element to wrap - **type** (Monad) - Optional - Element monad type - **block** (Proc) - Optional - Block to wrap (if value not given) ### Returns - **List** - A new List instance ``` -------------------------------- ### Transform Task>> Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Demonstrates using fmap3 to chain an operation with a Task containing a List of Results. ```ruby task = Task do List[Success(1), Success(2), Failure(:error)] end task.fmap3 { |x| x + 100 } # Chains async operation with list transformation ``` -------------------------------- ### to_s / inspect Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Returns the string representation of the Try::Error object. ```APIDOC ## to_s / inspect ### Description Returns a string representation of the error, including the exception class and message. ### Returns - (String) - Format: "Try::Error(ExceptionClass: message)" ``` -------------------------------- ### Failure#bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Short-circuits the operation and returns the Failure instance unchanged. ```APIDOC ## bind(*args, &block) ### Description Short-circuits, returns self unchanged. ### Returns - **self** ``` -------------------------------- ### Data Processing Pipelines Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Chaining transformations on results using fmap2. ```ruby fetch_results.fmap2 { |item| item.upcase } .fmap2 { |item| validate_format(item) } .fmap2 { |item| store(item) } ``` -------------------------------- ### maybe Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Similar to fmap but explicitly handles nil results without triggering deprecation warnings. ```APIDOC ## maybe(*args, &block) ### Description Like fmap but explicitly handles nil result. No deprecation warning. ### Parameters - **args** (Array) - Optional - Arguments passed to callable - **block** (Proc) - Optional - Block to apply ### Returns Maybe::Some or Maybe::None ### Example ```ruby Some(4).maybe { |x| x + 1 } # => Some(5) Some(4).maybe { |_| nil } # => None() ``` ``` -------------------------------- ### Transform Maybe> Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Demonstrates using fmap2 to transform a List wrapped in a Maybe. ```ruby maybe = Some(List[1, 2, 3]) maybe.fmap2 { |x| x * 2 } # => Some(List[2, 4, 6]) ``` -------------------------------- ### Try.pure Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Wraps a value or block with a Try::Value without performing exception handling. ```APIDOC ## Try.pure(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) ### Description Wraps a value or block with Value (no exception handling). ### Parameters - **value** (Object) - Optional - Value to wrap - **exceptions** (Array) - Optional - Exception types for this value - **block** (Proc) - Optional - Block to wrap (if value not given) ### Returns - **Try::Value** ### Example Try.pure(42) # => Try::Value(42) Try.pure { 42 } # => Try::Value(42) ``` -------------------------------- ### Transform List> Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/transformer.md Demonstrates using fmap2 to transform values inside a List of Results. ```ruby list = List[Success(1), Success(2), Failure(:error)] list.fmap2 { |x| x + 10 } # => List[Success(11), Success(12), Failure(:error)] # Without fmap2: list.fmap { |result| result.fmap { |x| x + 10 } } ``` -------------------------------- ### Configure Deprecation Warnings Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/configuration.md Use Dry::Core::Deprecations to define and track deprecated methods within the library. ```ruby extend Core::Deprecations[:"dry-monads"] deprecate :old_method, :new_method ``` -------------------------------- ### Define to_proc method signature Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/result.md Returns a proc that constructs new Failure instances. ```ruby Failure.to_proc() ``` -------------------------------- ### Applicative Application Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/right-biased.md Applies multiple wrapped values to a function wrapped in a Success monad. ```ruby Success { |a, b, c| a + b + c } .apply(Success(1)) .apply(Success(2)) .apply(Success(3)) .value! # => 6 ``` -------------------------------- ### Handling Failures with or Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/right-biased.md Yields the failure value to a block or returns a provided fallback value. ```ruby Failure(:error).or { :fallback } # => :fallback None().or(42) # => 42 Failure(:e).or { |e| "Error: #{e}" } # => "Error: e" ``` -------------------------------- ### Using Do Notation with Try Monad Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Integrates the Try monad to handle exceptions and convert them into results for use with Do notation. ```ruby include Dry::Monads[:result, :try, :do] include Dry::Monads::Do.for(:parse_and_process) def parse_and_process(json_string) json = yield Try(JSON::ParserError) { JSON.parse(json_string) }.to_result validated = yield validate_json(json) Success(validated) end ``` -------------------------------- ### Configure Maybe nil coercion warnings Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/maybe.md Toggle warnings for implicit nil coercion when using fmap. ```ruby Dry::Monads::Maybe.warn_on_implicit_nil_coercion(false) # Disable warnings ``` -------------------------------- ### Chain Tasks with bind Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Monadic bind that allows chaining a block returning another Task. ```ruby Task { 10 }.bind { |x| Task { x * 2 } }.value! # => 20 ``` -------------------------------- ### Pattern matching on results Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/errors.md Uses Ruby's case-in pattern matching to branch logic based on Success or Failure states. ```ruby case operation in Success(value) handle_success(value) in Failure(error) handle_error(error) end ``` -------------------------------- ### Recover from Task error with or Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/task.md Rescues an error by returning a replacement Task. ```ruby task = Task { 1 / 0 } task.or { |e| Task { "handled: #{e.class}" } }.value! # => "handled: ZeroDivisionError" ``` -------------------------------- ### Transaction Blocks with Do Notation Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/do.md Illustrates a transactional flow where any failure in the sequence halts execution. ```ruby include Dry::Monads::Do.for(:transaction) def transaction user = yield @repo.create_user(data) yield @repo.assign_role(user, :admin) yield send_confirmation(user.email) Success(user) end # If any operation fails, all changes are rolled back result = @service.transaction ``` -------------------------------- ### Try[] Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/api-reference/try.md Convenience operator to run code with exception handling. ```APIDOC ## Try[*exceptions, &block] ### Description Convenience operator to run code with exception handling. ### Parameters - **exceptions** (Array) - Required - Exception classes to rescue - **block** (Proc) - Required - Code block to execute ### Returns - **Try::Value** or **Try::Error** ### Raises - **ArgumentError** if no exceptions specified ### Example Try[ZeroDivisionError] { 10 / 2 } # => Try::Value(5) Try[ZeroDivisionError] { 10 / 0 } # => Try::Error ``` -------------------------------- ### Pattern Matching with Monads Source: https://github.com/dry-rb/dry-monads/blob/main/_autodocs/types.md Monads support Ruby 3.0+ pattern matching syntax. ```ruby case monad_value in Success(Integer) # ... in Success(String => str) # ... in Failure(error) # ... end ```