These are chat archives for dry-rb/chat

21st
Dec 2018
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:05
Hello, How do I get transform_keys(&:to_sym) to work with nested structs? It works fine with 1st level attributes.
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:06
create and use the same base class across your structs
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:17
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:19
similar but I think you want to nested structs rather nested schemas
class MyStruct < Base
  attribute :id, Types::Strict::Integer
  attribute :data do
    attribute :code, Types::Strict::Integer.optional.default(nil)
    attribute :msg,  Types::String.optional.default(nil)
  end
end
like that^
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:24
MyStruct.new({"id" => 1, "data" => { "code" => 200 }}) still doesn't set the code attribute :/
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:24
lemme look into this
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:25
but thanks for the nested structs hint :)
cool
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:29
change, attribute :data do to attribute(:data, Base) do
because it's not usign Base as default there but Dry::Struct
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:30
yes, was about to write that solution :)
can there be an argument for having nested structs inherit from parent struct?
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:34
we could have a means for that
I'm not sure what's the best here but having something would be nice
I came across this pattern a copule of times
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:36
Thanks for helping out
oh btw, can a nested struct be optional like a nested schema?
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:39
you mean absence of key or nil as a value?
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:40
I have Types::Hash.schema( ... ).optional.default(nil) in some structs
Nikita Shilnikov
@flash-gordon
Dec 21 2018 13:45
class MyStruct < Base
  attribute :id, Types::Strict::Integer
  attribute :data, Class.new(Base) {
    attribute :code, Types::Strict::Integer.optional.default(nil)
    attribute :msg,  Types::String.optional.default(nil)
  }.optional
end
that's the closest thing I can think of
and that's not good enough
feel free to post both suggestions to GH and we'll sort it out eventually
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:47
will do, thx
Tonni Tølbøll Lund Aagesen
@ta
Dec 21 2018 13:56
oh my, what one can learn from reading the docs more closely: Types::Hash.schema(name: Types::Strict::String).with_key_transform(&:to_sym) :)
Nikita Shilnikov
@flash-gordon
Dec 21 2018 14:33
yeah, if you don't need structs you can use schemas, they also support kind of inheritance
I prefer DSL for describing structs, this is basically it