These are chat archives for dry-rb/chat

11th
Dec 2017
Opan Mustopah
@opan
Dec 11 2017 08:35
Hi guys, is it possible to use Dry::Struct like this way?
class Foo < Dry::Struct
  # I reference the class with string
  # Just like active record do when we define relation in model
  attribute :bar, 'Zoo'
end
Well I need this feature because I have a problem when I trying to load these files.
let say if Foo is loaded first than Zoo, then if I define like the standar way, it would be trigger an error that said Zoo is undefined or something because Zoo is not loaded yet, except I define require_relative 'zoo' on top of foo.rb file and I want to avoid this.
Is it possible to do? Thanks in advance
Tim Riley
@timriley
Dec 11 2017 09:57
@opan we don’t support that, no. We encourage you to require files you need :)
Adding require or require_relative for any other constants I need to refer to (like Zoo in your case) to the top of my struct class files is exactly what I do in my apps.
Opan Mustopah
@opan
Dec 11 2017 10:00
I see, thanks @timriley for your answer
Chris Richards
@cmrichards
Dec 11 2017 14:04
With dry-rb validation, how would I validate that 2 dates aren't more than 2 months apart?
Sean Winner
@swinner2
Dec 11 2017 17:41
in dry-validation. If I use type_specs = true do I have to declare a type for each rule? Any way to only define a type spec for one rule?
Tim Riley
@timriley
Dec 11 2017 21:26
@swinner2 you have to declare a spec for every key, yeah
Tim Riley
@timriley
Dec 11 2017 21:38
@cmrichards something like this?
require "dry/validation"
require "time_math"

schema = Dry::Validation.Schema do
  configure do
    def self.messages
      super.merge(en: {errors: {ends_at_within_two_weeks_of_starts_at: 'must be within two weeks of start time'}})
    end
  end

  required(:starts_at).filled(:time?)
  required(:ends_at).filled(:time?)

  validate(ends_at_within_two_weeks_of_starts_at: [:starts_at, :ends_at]) do |starts_at, ends_at|
    two_weeks = 2 * 7 * 24 * 60

    (ends_at - starts_at) <= two_weeks
  end
end

valid_input = {
  starts_at: TimeMath.day.decrease(Time.now, 10),
  ends_at: Time.now,
}

schema.(valid_input).messages
# => {}

invalid_input = {
  starts_at: TimeMath.day.decrease(Time.now, 20),
  ends_at: Time.now,
}

schema.(invalid_input).messages
# => {:ends_at_within_two_weeks_of_starts_at=>["must be within two weeks of start time"]}
I did two weeks instead of two months, but you get the idea
Sean Winner
@swinner2
Dec 11 2017 22:01
@timriley I’m trying to find a way to make the default type_spec Types::Anysorry I’m pretty new to dry-validation. Is there an easy way to go about this?
Tim Riley
@timriley
Dec 11 2017 22:43
@swinner2 why are you trying to avoid specifying stricter types? The whole idea of dry-validation is to avoid such looseness as comes with an “any” type.