These are chat archives for dry-rb/chat

4th
Oct 2018
Tim Riley
@timriley
Oct 04 2018 01:43
@pablocrivella you want dry-auto_inject for that
Pablo Crivella
@pablocrivella
Oct 04 2018 08:17
@timriley Yeah i checked that one but i’m having a hard time wrapping my head around how it should be the correct way of including it on a rails project.
For now i went for the “hybrid” approach:
# frozen_string_literal: true

require "dry/transaction/operation"

class CheckAccess
  include Dry::Transaction::Operation

  def initialize(check_purchase: CheckPurchase.new)
    @check_purchase = check_purchase
  end

  def call(user)
    return Success(user.licenses.first) if active_license_for?(user)

    @check_purchase.call(user.purchases.first).or(
      if user.on_trial?
        Success(Trial.new(user: user))
      else
        Failure(user)
      end
    )
  end

  private

  def active_license_for?(user)
    user.licenses.first_or_initialize.active?
  end
end
David Dawson
@DangerDawson
Oct 04 2018 08:22
@pablocrivella I take a similar approach, plus you can always use the following gem: https://github.com/dry-rb/dry-initializer for your initializer
Matheus Silva Santos de Oliveira
@matheussilvasantos
Oct 04 2018 14:14
Does someone know how to validate an optional field with a set of values?
I found this in documentation required(:sample).value(eql?: 1234), but I the field I want to validate is optional and there is more than one value that it could be.
Piotr Solnica
@solnic
Oct 04 2018 14:18
@matheussilvasantos required(:sample).maybe(included_in?: [1, 2, 3])
Matheus Silva Santos de Oliveira
@matheussilvasantos
Oct 04 2018 14:22
@solnic thank you!!
Igor Alexandrov
@igor-alexandrov
Oct 04 2018 14:34
@matheussilvasantos if you have optional key (it may be missed in input) then you should use optional instead of required
optional(:sample).maybe(included_in?: [1, 2, 3])
Igor Alexandrov
@igor-alexandrov
Oct 04 2018 17:50
irb(main):013:0> VALUE = 1
=> 1
irb(main):014:0> Dry::Monads::Success(Dry::Monads::Success(VALUE))
=> Success(Success(1))
I always thought that it should be just Success(1)
Igor Alexandrov
@igor-alexandrov
Oct 04 2018 17:57
Don't know maybe #flatten or #compact should be added for such cases
Nikita Shilnikov
@flash-gordon
Oct 04 2018 17:59
you usually use fmap/bind depending on the case, there's no flatten/join because it's normally not required
flattening by default will ruin the semantics
it won't "type check"
Igor Alexandrov
@igor-alexandrov
Oct 04 2018 18:10
Ok, got it
Thanks!
Igor Alexandrov
@igor-alexandrov
Oct 04 2018 18:56
The question above was because we tried to combine Try and Result monads, but we found a solution:
irb(main):003:0> Try { Failure(5) }.to_result.bind(&:itself)
=> Failure(5)
irb(main):004:0> Try { raise RuntimeError.new }.to_result.bind(&:itself)
=> Failure(#<RuntimeError: RuntimeError>)
irb(main):005:0> Try { Success(1) }.to_result.bind(&:itself)
=> Success(1)