Use pattern matching with controller helpers example#54
Use pattern matching with controller helpers example#54diegotoral wants to merge 1 commit intodry-rb:mainfrom
Conversation
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.
|
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 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 |
| render json: { code: code, errors: errors.to_h }, status: :unprocessable_entity | ||
| end | ||
| case resolve("users.create").(safe_params[:user]) | ||
| in Success[user] |
There was a problem hiding this comment.
Returning user within an array makes no sense here, since we are creating a single user
There was a problem hiding this comment.
In a production app me might assume that Dry::Monads has been included already, but that will create confusion in a document example.
| case resolve("users.create").(safe_params[:user]) | ||
| in Success[user] | ||
| render json: user | ||
| in Failure[code, errors] |
There was a problem hiding this comment.
It would be neat to demonstrate how much more specific pattern-matching can be compared to dry-matcher
| in Success[user] | ||
| render json: user | ||
| in Failure[code, errors] | ||
| render json: { code: code, errors: errors.to_h }, status: :unprocessable_entity |
There was a problem hiding this comment.
A pattern-matcher should always be exhaustive, otherwise you'll raise a very unhelpful exception.
|
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 |
|
Perhaps it's time to break this up into sections, rather than one long page? |
Yes this should be broken down into sub-sections 🙂 |
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.