Last active
September 13, 2020 17:41
-
-
Save arefaslani/ff9d83a672d83a0efef522c815899556 to your computer and use it in GitHub Desktop.
Medium 702687394e3d-add-result-matcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dry/matcher/result_matcher' | |
module Posts | |
class Create | |
include Dry::Monads[:result, :do] | |
ValidationSchema = Dry::Schema.Params do | |
required(:title).filled(:str?) | |
optional(:body).maybe(:str?) | |
end | |
def self.call(params, &block) | |
service_outcome = self.new.execute(params) | |
if block_given? | |
Dry::Matcher::ResultMatcher.call(service_outcome, &block) | |
else | |
service_outcome | |
end | |
end | |
private | |
def execute(params) | |
yield validate_params(params) | |
create_post(params) | |
end | |
def validate_params(params) | |
validation_outcome = ValidationSchema.call(params) | |
return Failure(validation_outcome.errors.to_h) if validation_outcome.failure? | |
Success() | |
end | |
def create_post(params) | |
post = Post.create(params) | |
Success(post) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment