diff --git a/docsite/source/configuration.html.md b/docsite/source/configuration.html.md new file mode 100644 index 0000000..1671980 --- /dev/null +++ b/docsite/source/configuration.html.md @@ -0,0 +1,66 @@ +--- +title: Configuration +layout: gem-single +name: dry-operation +--- + +By default, `dry-operation` automatically wraps the `#call` method of your operations with failure tracking and error handling. This means you can use `#step` directly in your `#call` method without explicitly wrapping it in an otherwise necessary `steps do ... end` block. + +```ruby +class CreateUser < Dry::Operation + def call(input) + # This works automatically + user = step create_user(input) + step notify(user) + user + end +end +``` + +### Customizing wrapped methods + +You can customize which methods get automatically wrapped using the `.operate_on` class method: + +```ruby +class CreateUser < Dry::Operation + # Wrap both #call and #process methods + operate_on :call, :process + + def call(input) + step validate(input) + end + + def process(input) + step transform(input) + end +end +``` + +### Disabling automatic wrapping + +If you want complete control over method wrapping, you can disable the automatic wrapping entirely using `.skip_prepending`. In that case, you'll need to wrap your methods manually with `steps do ... end`: + +```ruby +class CreateUser < Dry::Operation + skip_prepending + + def call(input) + # Now you must explicitly wrap steps + steps do + user = step create_user(input) + step notify(user) + user + end + end +end +``` + +### Inheritance behaviour + +Both `.operate_on` and `.skip_prepending` configurations are inherited by subclasses. This means: + +- If a parent class configures certain methods to be wrapped, subclasses will inherit that configuration + +- If a parent class skips prepending, subclasses will also skip prepending + +- Subclasses can override their parent's configuration by calling `.operate_on` or `.skip_prepending` diff --git a/docsite/source/design-pattern.html.md b/docsite/source/design-pattern.html.md new file mode 100644 index 0000000..ab30bd5 --- /dev/null +++ b/docsite/source/design-pattern.html.md @@ -0,0 +1,37 @@ +--- +title: Design Pattern +layout: gem-single +name: dry-operation +--- + +`dry-operation` implements a pattern that closely resembles monadic composition, particularly the `Result` monad, and the Railway-oriented Programming pattern. Understanding these monadic concepts can provide deeper insight into how `dry-operation` works and why it's designed this way. + +### Monadic Composition + +In functional programming, a monad is a structure that represents computations defined as sequences of steps. A key feature of monads is their ability to chain operations, with each operation depending on the result of the previous one. + +`dry-operation` emulates this monadic behavior through its `#step` method and the overall structure of operations. + +In monadic terms, the `#step` method in `Dry::Operation` acts similarly to the `bind` operation: + +1. It takes a computation that may succeed or fail (returning `Success` or `Failure`). + +1. If the computation succeeds, it extracts the value and passes it to the next step. + +1. If the computation fails, it short-circuits the entire operation, skipping subsequent steps. + +This behavior allows for clean composition of operations while handling potential failures at each step. + +### Railway-oriented Programming + +The design of `dry-operation` closely follows the concept of Railway-oriented Programming, a way of structuring code that's especially useful for dealing with a series of operations that may fail. + +In this model: + +- The "happy path" (all operations succeed) is one track of the railway. + +- The "failure path" (any operation fails) is another track. + +Each step is like a switch on the railway, potentially diverting from the success track to the failure track. + +`dry-operation` implements this pattern by allowing the success case to continue down the method, while immediately returning any failure, effectively "switching tracks". diff --git a/docsite/source/error-handling.md b/docsite/source/error-handling.md new file mode 100644 index 0000000..5f6a6af --- /dev/null +++ b/docsite/source/error-handling.md @@ -0,0 +1,52 @@ +--- +title: Error Handling +layout: gem-single +name: dry-operation +--- +When using `dry-operation`, errors are handled through the `Failure` type from [`dry-monads`](/gems/dry-monads/). Each step in your operation should return either a `Success` or `Failure` result. When a step returns a `Failure`, the operation short-circuits, skipping the remaining steps and returning the failure immediately. + +You'll usually handle the failure from the call site, where you can pattern match on the result to handle success and failure cases. However, sometimes it's useful to encapsulate some error handling logic within the operation itself. + +### Global error handling + +You can define a global failure handler by implementing an `#on_failure` method in your operation class: + +```ruby +class CreateUser < Dry::Operation + def call(input) + attrs = step validate(input) + user = step persist(attrs) + step notify(user) + user + end + + def on_failure(failure) + # Log or handle the failure globally + logger.error("Operation failed: #{failure}") + end +end +``` + +The `#on_failure` method can optionally accept a second argument that indicates which method encountered the failure, allowing you more granular control over error handling: + +```ruby +class CreateUser < Dry::Operation + def call(input) + attrs = step validate(input) + user = step persist(attrs) + step notify(user) + user + end + + def on_failure(failure, step_name) + case step_name + when :validate + logger.error("Validation failed: #{failure}") + when :persist + logger.error("Persistence failed: #{failure}") + when :notify + logger.error("Notification failed: #{failure}") + end + end +end +``` diff --git a/docsite/source/extensions.html.md b/docsite/source/extensions.html.md new file mode 100644 index 0000000..39aac92 --- /dev/null +++ b/docsite/source/extensions.html.md @@ -0,0 +1,189 @@ +--- +title: Extensions +layout: gem-single +name: dry-operation +--- + +### ROM + +The `ROM` extension adds transaction support to your operations when working with [`rom-rb.org`](https://rom-rb.org). When a step returns a `Failure`, the transaction will automatically roll back, ensuring data consistency. + +First, make sure you have `rom-sql` installed: + +```ruby +gem 'rom-sql' +``` + +Include the extension in your operation class and provide access to the ROM container: + +```ruby +class CreateUser < Dry::Operation + include Dry::Operation::Extensions::ROM + + attr_reader :rom + + def initialize(rom:) + @rom = rom + super() + end + + def call(input) + transaction do + user = step create_user(input) + step assign_role(user) + user + end + end + + private + + def create_user(input) + Success(rom.relations[:users].command(:create).(input)) + end + + def assign_role(user) + Success(rom.relations[:roles].command(:create).(user_id: user.id, name: 'member')) + end +end +``` + +By default, the `:default` gateway will be used. You can specify a different gateway either when including the extension: + +```ruby +include Dry::Operation::Extensions::ROM[gateway: :my_gateway] +``` + +Or at runtime: + +```ruby +transaction(gateway: :my_gateway) do + # ... +end +``` + +### Sequel + +The `Sequel` extension provides transaction support for operations using [`sequel` databases](http://sequel.jeremyevans.net). It will automatically roll back the transaction if any step returns a Failure. + +Make sure you have sequel installed: + +```ruby +gem 'sequel' +``` + +Include the extension in your operation class and provide access to the Sequel database object through a `#db` method: + +```ruby +class CreateUser < Dry::Operation + include Dry::Operation::Extensions::Sequel + + attr_reader :db + + def initialize(db:) + @db = db + super() + end + + def call(input) + transaction do + user_id = step create_user(input) + step create_profile(user_id) + user_id + end + end + + private + + def create_user(input) + Success(db[:users].insert(input)) + end + + def create_profile(user_id) + Success(db[:profiles].insert(user_id: user_id)) + end +end +``` + +You can pass options to the transaction either when including the extension: + +```ruby +include Dry::Operation::Extensions::Sequel[isolation: :serializable] +``` + +Or at runtime: + +```ruby +transaction(isolation: :serializable) do + # ... +end +``` + +⚠️ Warning: The ``:savepoint` option for nested transactions is not yet fully supported. + +### ActiveRecord + +The `ActiveRecord` extension adds transaction support for operations using [`activerecord`](https://api.rubyonrails.org/classes/ActiveRecord). Like the other database extensions, it will roll back the transaction if any step returns a `Failure`. + +Make sure you have activerecord installed: + +```ruby +gem 'activerecord' +``` + +Make sure you have activerecord installed: + +```ruby +class CreateUser < Dry::Operation + include Dry::Operation::Extensions::ActiveRecord + + def call(input) + transaction do + user = step create_user(input) + step create_profile(user) + user + end + end + + private + + def create_user(input) + Success(User.create!(input)) + end + + def create_profile(user) + Success(user.create_profile!) + end +end +``` + +By default, `ActiveRecord::Base` is used to initiate transactions. You can specify a different class either when including the extension: + +```ruby +include Dry::Operation::Extensions::ActiveRecord[User] +``` + +Or at runtime: + +```ruby +transaction(User) do + # ... +end +``` + +This is particularly useful when working with multiple databases in `ActiveRecord`. + +You can also provide default transaction options when including the extension: + +```ruby +include Dry::Operation::Extensions::ActiveRecord[isolation: :serializable] +``` + +You can override these options at runtime: + +```ruby +transaction(isolation: :serializable) do + # ... +end +``` + +⚠️ Warning: The `:requires_new` option for nested transactions is not yet fully supported. diff --git a/docsite/source/index.html.md b/docsite/source/index.html.md new file mode 100644 index 0000000..47a8ff7 --- /dev/null +++ b/docsite/source/index.html.md @@ -0,0 +1,97 @@ +--- +title: Introduction +layout: gem-single +type: gem +name: dry-operation +sections: + - error-handling + - configuration + - extensions + - design-pattern +--- +`dry-operation` is a lightweight DSL that wraps around [`dry-monads`](/gems/dry-monads/), allowing you to chain operations with a focus on the happy path while elegantly handling failures. + +### Introduction + +In complex business logic, it's common to have a series of operations that depend on each other. Traditionally, this leads to deeply nested conditional statements or a series of guard clauses. `dry-operation` provides a more elegant solution by allowing you to define a linear flow of operations, automatically short-circuiting on failure. + +### Basic Usage + +To use `dry-operation`, create a class that inherits from `Dry::Operation` and define your flow in the `#call` method: + +```ruby +class CreateUser < Dry::Operation + def call(input) + attrs = step validate(input) + user = step persist(attrs) + step notify(user) + user + end + + private + + def validate(input) + # Return Success(attrs) or Failure(error) + end + + def persist(attrs) + # Return Success(user) or Failure(error) + end + + def notify(user) + # Return Success(true) or Failure(error) + end +end +``` + +In this example, each step (`validate`, `persist`, `notify`) is expected to return either a `Success` or `Failure` monad from [`dry-monads`](/gems/dry-monads/). + +### The step method + +The step method is the core of `Dry::Operation`. It does two main things: + +- If the result is a `Success`, it unwraps the value and returns it. + +- If the result is a `Failure`, it halts the execution throwing the failure up the call stack. + +This behavior allows you to write your happy path in a linear fashion, without worrying about handling failures at each step. + +### The call method + +The `#call` method will catch any potential failure from the steps and return it. If it completes without encountering any failure, its return value is automatically wrapped in a `Success` monad. This means you don't need to explicitly return a `Success` at the end of your `#call` method. + +For example, given this operation: + +```ruby +class CreateUser < Dry::Operation + def call(input) + attrs = step validate(input) + user = step persist(attrs) + step notify(user) + user # This is automatically wrapped in Success + end + + # ... other methods ... +end +``` + +When all steps succeed, calling this operation will return `Success(user)`, not just `user`. + +### Handling Results + +After calling an operation, you get back a Result monad. You can pattern match on this result to handle success and failure cases: + +```ruby +case CreateUser.new.(input) +in Success(user) + puts "User #{user.name} created successfully" +in Failure[:invalid_input, errors] + puts "Invalid input: #{errors}" +in Failure(:database_error) + puts "Database error occurred" +in Failure(:notification_error) + puts "User created but notification failed" +end +``` + +This pattern matching allows you to handle different types of failures in a clear and explicit manner. diff --git a/spec/integration/extensions/sequel_spec.rb b/spec/integration/extensions/sequel_spec.rb index e90768d..0f96631 100644 --- a/spec/integration/extensions/sequel_spec.rb +++ b/spec/integration/extensions/sequel_spec.rb @@ -115,6 +115,32 @@ def create_user instance.() end + it "works with `auto_savepoint` in the outer transaction" do + instance = Class.new(base) do + def call + transaction(auto_savepoint: true) do + step create_user + transaction do + step failure + end + end + end + + def create_user + Success(db[:users].insert(name: "John")) + end + + def failure + Failure(:failure) + end + end.new(db: db) + + instance.() + + expect(db[:users].count).to be(1) + end + + xit "works with `savepoint` for nested transactions" do instance = Class.new(base) do def call