Home > Software design >  Rails 6 monads pattern matching to fetch only success/failure
Rails 6 monads pattern matching to fetch only success/failure

Time:05-19

Is there any build in or some nifty way to fetch only Success or Failure results from array of monad results?

e.g.

state
=> [Failure("12345 Product code is not valid"), Success("eiowruqoiu Backbone Product created")]

where

state[0].class
=> Dry::Monads::Result::Failure
state[1].class
=> Dry::Monads::Result::Success

CodePudding user response:

state.grep(Dry::Monads::Result::Failure)
state.grep(Dry::Monads::Result::Success)

or

state.select { |s| s.is_a?(Dry::Monads::Result::Failure) }
state.select { |s| s.is_a?(Dry::Monads::Result::Success) }

or using success? / failure? monads methods

state.select(&:success?)
state.select(&:failure?)
state.reject(&:success?)
state.reject(&:failure?)
  • Related