Custom Dry::Matcher

Hi all! I would like to know is there is a better way to implement a FailureCase like that bellow:

FailureCase = Dry::Matcher::Case.new do |value, patterns|
  failure = value.failure

  if failure.respond_to?(:keys) and patterns.include?(failure.keys.first)
    failure.values.first
  elsif patterns.empty?
    failure
  else
    Dry::Matcher::Undefined
  end
end

The is idea is to use like this: Failure(validation_error: “My error”) or just Failure(“My generic error”)

I recommend using failure tuples for this. They already work as-is with Dry::Matcher::ResultMatcher.

Dry::Matcher::ResultMatcher.(Failure[:validation_error, "My error"]) do |on|
  on.success { ... }

  on.failure :validation_error do |_, msg|
    puts msg
  end

  on.failure { ... }
end

Every failure result I return, I give it a name like this. It makes nesting and pattern-matching errors pretty simple.

This pattern also works as-is with case..in matching.

case Failure[:validation_error, "My error"]
in Success(value)
  # do something with value
in Failure[:validation_error, msg]
  puts msg
end
2 Likes

@alassek Thank you!