DEV Community

Mengjia L
Mengjia L

Posted on

Ruby dry-monads

  • 🤔 What is the use case for dry-monads?
  • 😀 return either Success or Failure from some operation

From the dry-monads doc:

Monads provide an elegant way of handling errors, exceptions and chaining functions so that the code is much more understandable and has all the error handling without all the ifs and elses

user = User.find_by(id: params[:id])

if user
  address = user.address
end

if address
  city = address.city
end

if city
  state = city.state
end

if state
  state_name = state.name
end

user_state = state_name || "No state"
Enter fullscreen mode Exit fullscreen mode

After using dry-monads ✨

def find_user(user_id)
  user = User.find_by(id: user_id)

  if user
    Success(user)
  else
    Failure(:user_not_found)
  end
end

def find_address(address_id)
  address = Address.find_by(id: address_id)

  if address
    Success(address)
  else
    Failure(:address_not_found)
  end
end
Enter fullscreen mode Exit fullscreen mode

This style of programming is called 🚃 Oriented Programming ( Railway Oriented Programming) - More info here!

Top comments (0)