I would like to be able to do attribute :people, type: Array[Person]
and have each member of the array coerced to a Person
.
Here is a fuller example:
class Person
attr_reader :name
def initalize(attributes);
@name = attributes.fetch(:name)
end
end
class MyForm
include Lotus::Validations
attribute :people, type: Array[Person]
end
form = MyForm.new(people: [{ name: 'Kris', name: 'Lindsey' }]
form.people.first.name # => 'Kris'
form.people.all? { |p| p.is_a?(Person) } # => true
I hacked together a very simple solution here: https://github.com/lotus/validations/pull/68
The above might be enough for now (I’d think a bit harder and add tests) or you might already have some thoughts on this already.
Another similar use case might be a Hash which has cocershed key/values, so you might want:
attribute :address, Hash(Symbol => String)
However I’m not sure this would be typical since all keys/values have be to of the same type, which would only work for simple cases and more likely you would use an object so attribute :address, Address
.
Another approach might be to add a collection
key to attribute
so something like attribute :people, type: Person, collection: true
. But I don’t see this as any better, just a different DSL.