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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay