Unable to create a dry-struct from a hash with string keys


#1

If I have a hash

{ "name" => "Bob", "age" => 12 }

with a class

class DryUser < Dry::Struct
  attribute :name, Types::String
  attribute :age,  Types::Int
end

The attributes are not being set correctly.

irb(main):172:0> DryUser.new("name" => "Bob", "age" => 12)
=> #<DryUser name=nil age=nil>
irb(main):173:0>

This works with Virtus

class VirtusUser
  include Virtus.model

  attribute :name, String
  attribute :age,  Int
end
irb(main):197:0> VirtusUser.new("name" => "Bob", "age" => 12)
=> #<VirtusUser:0x00007f829ea663f0 @name="Bob", @age=12>

How do I make this work with dry-struct? I searched the documentation and found constructor_type :symbolized, but that didn’t work with dry-struct.

I know these gems aren’t the same but this feels like a common use case and would appreciate any help you all can offer. Thanks!


#2

It will be available in the next version, see for more information https://github.com/dry-rb/dry-struct/pull/64


#3

That’s great news. To confirm, in the next version, I’d use transform_keys to convert the hash keys into symbols, correct?


#4

Yes.


Here’s an unrelated text because our discourse doesn’t allow messages less than 20 characters long /cc @solnic


#5

Updated it to minimum 2. Now you can say “Yes” or “No”, @flash-gordon :laughing: (/cc @solnic)