I’ve been playing around with dry-struct
yesterday, and found nothing quite as compact as the following shorthand used with normal Ruby structs:
Person = Struct.new(:age, :name)
Since there are already some capitalized methods that act like “type constructors” in dry-rb
, I added a “factory method”, Dry.Struct
:
Person = Dry.Struct(name: Types::String, age: Types::Int)
p = Person[name: "Test", age: 42]
#=> #<Person name="Test" age=42>
p.class
#=> Person
Like a standard dry-struct
this defaults to :permissive
, though you can override that easily:
Test = Dry.Struct(:strict, expected: Types::String)
Test[expected: "foo", unexpected: "bar"]
#=> Dry::Struct::Error: [Test.new] unexpected keys [:unexpected] in Hash input
Last but not least there’s the block form, which is nice if you want to be a bit more explicit/have longer attribute definitions with defaults etc. (contrived example):
AllTheThings = Dry.Struct(:strict, name: Types::String) do
attribute :age, Types::Strict::Int.optional
end
So before I go ahead and spend time adding YARD docs and adding some tests to open a PR, does anyone else like this form? If you find the class method on the Dry
module weird, I also experimented with Dry::Struct.make(...)
but preferred the former. I’m open though.