How do I get thing.attributes to create hashes for embedded items?

Hi there,

I’m very new to dry-rb, just discovered it tonight after looking for something that might make building “models” for an app I’m working on a little easier since I don’t want to use Rails for this. I was quite excited when I found dry-struct, and converted a lot of the stuff I already had to use it since it would greatly simplify things.

…or so I thought.

Here’s what I have:

class Command < Dry::Struct
  attribute :id,        Types::String.optional
  attribute :server_id, Types::String
  attribute :user_id,   Types::String
  attribute :command,   Types::String
  attribute :stderr,    Types::Array do
    attribute :output,  Types::String.optional
    attribute :at,      Types::DateTime.optional
  end
  attribute :stdout,    Types::Array do
    attribute :output,  Types::String.optional
    attribute :at,      Types::DateTime.optional
  end
end

I want to call .attributes on something and be able to get a full hash for the attributes on that object. I have to have this to be able to work with my project’s database (RethinkDB).

This works fine for shallow objects, but when you have something that has embedded arrays and such, it’s not nearly so smooth and I can’t use the data that comes out of it because it won’t parse cleanly:

See how the stuff under “stdout” and “stderr” isn’t a hash but a representation of an object? I want ALL of it to be a hash, no matter how deep it gets. How would I do that with dry-struct?

(I apologize if this is a common or “RTFM” question, there’s a lot of modules to go through and I’ve been awake for almost 3 days straight now, so I may have just missed it. Any suggestions you can offer would be much appreciated.)

Call .to_h :slight_smile:

1 Like

OMFG. Wow. Talk about the simplest possible solution! Thank you, flash!