Last active
May 16, 2021 02:00
Rails example for dry-transaction and dry-validation
This file contains hidden or 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
# app/controllers/users_controller.rb | |
class UsersController < ApplicationController | |
def create | |
Operations::User::Create.new.call(params[:user]) do |m| | |
m.success do |user_response| | |
render json: user_response | |
end | |
m.failure do |responce| | |
render json: responce, status: :not_acceptable | |
end | |
end | |
end | |
end | |
# app/operations/user/create.rb | |
require 'dry/transaction' | |
module Operations::User | |
class Create | |
include Dry::Transaction | |
include Dry::Monads::List::Mixin | |
VALIDATOR = Dry::Validation.Schema do | |
required(:nickname).filled | |
required(:email).filled | |
required(:password).filled | |
end | |
ALLOW_PARAMS = ::User.column_names.freeze | |
DENY_PARAMS = %i[id].freeze | |
step :validate | |
step :clean | |
try :persist, catch: StandardError | |
tee :log_data | |
def validate(user) | |
result = VALIDATOR.call(user) | |
result.success? ? Right(result) : Left(result.errors) | |
end | |
def clean(user) | |
Right(user.output.select! { |k, _v| ALLOW_PARAMS.include? k }.permit!.except(*DENY_PARAMS)) | |
end | |
def persist(user) | |
::User.create(user) | |
end | |
def log_data(user) | |
Rails.logger.info user.inspect | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment