Skip to content

Instantly share code, notes, and snippets.

@vadimstroganov
Last active May 16, 2021 02:00
Show Gist options
  • Save vadimstroganov/6291e8feda58376606e51f79fa123a02 to your computer and use it in GitHub Desktop.
Save vadimstroganov/6291e8feda58376606e51f79fa123a02 to your computer and use it in GitHub Desktop.
Rails example for dry-transaction and dry-validation
# 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