What am i doing wrong?

hello all :slight_smile:

I am getting the following error

ruby/3.1.1/lib/ruby/gems/3.1.0/gems/dry-monads-1.4.0/lib/dry/monads/do/mixin.rb:49:in `block in bind': undefined method `to_monad' for #<Dry::Validation::Result{:name=>"dave"} errors={}> (NoMethodError)

            monad = result.to_monad

when I run this simple example

#!/usr/bin/env ruby

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "dry-validation", "~> 1.8"
  gem "dry-monads", "~> 1.4"
end

require "dry/validation"
require "dry/monads"
require "dry/monads/do"

class Command
  include Dry::Monads[:result]
  include Dry::Monads::Do.for(:call)

  def call(params)
    values = yield validate(params)
    name = yield do_something(values)

    Success(name)
  end

  def validate(params)
    Contract.new.call(params)
  end

  def do_something(values)
    returns Success(values.name)
  end
end

class Contract < Dry::Validation::Contract
  params do
    required(:name).filled(:string)
  end
end

result = Command.new.call(name: "dave")

puts "The name: #{result.value!}"

Knowing me I have skipped over or misread some docs… but I am abit stuck, could some please point out the problem with the code

thanks for reading my plead for help :smiley:

1 Like

Hey Ben, you just need to load the monads extension for Dry Validation. Like this:

Dry::Validation.load_extensions :monads

You’ll also want to fix this method as follows:

def do_something(values) = Success(values[:name])

Now, when you run the script, it’ll work.

1 Like

arh! amazing, thanks so much.

1 Like