These are chat archives for dry-rb/chat

13th
Oct 2016
Ricardo Bernardeli
@bernardeli
Oct 13 2016 03:46
Hi guys! Hope you're all well. Playing with dry-struct and dry-types, and wanted to have an array with members of two types, where both types have same attribute BUT different type. Example below:
require "dry-struct"
require "dry-types"

module Types
  include Dry::Types.module
end

class Answer < Dry::Struct
  attribute :question_id, Types::String

  class Select < self
    attribute :value, Types::Hash.schema(id: Types::Int)
  end

  class Text < self
    attribute :value, Types::String
  end
end

class Survey < Dry::Struct
  attribute :answers, Types::Array.member(Answer::Text | Answer::Select)
end

Survey.new(
  answers: [
    Answer::Select.new(question_id: 1, value: {id: 10}),
    Answer::Text.new(question_id: 1, value: "foo")
  ]
)

#<Survey answers=[#<Answer::Text question_id=1 value={:id=>10}>, #<Answer::Text question_id=1 value="foo">]>
Problem here is, both answers came back as Answer::Text.
If I invert the order of the members to .member(Answer::Select | Answer::Text), things blow up.
The other thing I tried too is to have .member(Answer) since Select and Text are subclasses of Answer.
It doesn't blow up but turns Answer::Select into an Answer, getting rid of attribute :value.
Ricardo Bernardeli
@bernardeli
Oct 13 2016 03:52
How can I achieve members of an array to accepting subclasses of a type?
Appreciate if someone can shed some light for me! :)
Tim Riley
@timriley
Oct 13 2016 04:03
If you could both post these up to https://discuss.dry-rb.org, we’ll see if we can get some answers for you - this is where we’re trying to handle support questions like this.
Ricardo Bernardeli
@bernardeli
Oct 13 2016 04:05
Cool - will do!
Thanks Tim!
Tim Riley
@timriley
Oct 13 2016 04:10
:pray: