dry-rb / dry-rails

The official dry-rb railtie
https://dry-rb.org/gems/dry-rails
MIT License
270 stars 27 forks source link

Use pattern matching with controller helpers example #54

Open diegotoral opened 2 years ago

diegotoral commented 2 years ago

Previously we had examples using dry-matchers' syntax and it confused some users (including me) who expected examples to "just work" after adding the gem. Updates the example in the controller helpers section to use pattern matching instead.

alassek commented 2 years ago

I was just about to open my own PR for this, so why don't we combine efforts. I wrote something very similar but I think we should actually provide a working example, for instance there is no schema definition for safe_params and you need to include Dry::Monads into the controller for this to work.

While we're here, why not flesh out the pattern-match?

require "dry/monads"

class UsersController < ApplicationController
  include Dry::Monads[:result]

  schema(:create) do
    required(:user).hash do
      required(:name).filled(:string)
      required(:email).filled(:string)
    end
  end

  def create
    case resolve("users.create").(safe_params[:user])
    in Success(user)
      render json: user
    in Failure[Integer => code, Dry::Validation::Result => errors]
      render json: { code: code, errors: errors.to_h }, status: :unprocessable_entity
    in Failure(error)
      logger.warn "unhandled error: #{error.inspect}"
      render status: :internal_server_error
    end
  end
end
diegotoral commented 2 years ago

Thank you for the review @alassek! I really like your idea and think we can cooperate to update the examples.

I think all examples within the doc should be working examples, but you got me thinking if the controller helpers section would be the best place for this since the focus is the resolve method. :thinking:

alassek commented 2 years ago

Perhaps it's time to break this up into sections, rather than one long page?

solnic commented 2 years ago

Perhaps it's time to break this up into sections, rather than one long page?

Yes this should be broken down into sub-sections 🙂