Answers for "rails monad"

1

rails monad

# Sample of monad that creates a user
# but needs to validate first if the paramters
# are correct.

class CreateUser
  include Dry::Monads[:result, :do]

  def initialize(params)
    @params = params
  end

  def self.call(*args)
    new(*args).call
  end

  def call
    User.transaction do
    	user = yield valid_params?
        user = create_user(user)
        Success(user)
    end
  end

  private

  attr_reader :params

  def valid_params?
  	user = User.new(params)
    
	return Success(user) if User.new(user.valid?).valid?
    
    Failure(errors: user.errors)
  end
  
  def create_user(user)
  	return Success(user) if user.save
    
    Failure(errors: user.errors)
  end
end

# Example Usage of this Dry Monad Class

class UsersController
	def create
    	command = CreateUser.call(permitted_params)
        
        if command.success?
        	render json: command.success, status: :ok
        else
        	render errors: command.errors, status: :unprocessable_entity
        end
    end
end
Posted by: Guest on October-19-2021

Browse Popular Code Answers by Language