Hi,
I was wondering exactly the same things - how to have the final output of Dry Validation be a Struct instead of hash of data?
I need the struct so that I can afterwards place it in a rails form.
My intention is the same as Trailblazer Reform - http://trailblazer.to/gems/reform/ - but Reform seems to be a bit behind right now, and I wanted to do something simple with just Dry Validation and Dry Struct.
I’ve done it using something along the lines of this, but I wonder if there’s an even more elegant way:
class ApplicationForm
# Required dependency for ActiveModel::Errors
extend ActiveModel::Naming
extend ActiveModel::Translation
attr_reader :errors
def initialize(attributes = {})
assign_attributes(attributes) if attributes
@errors = ActiveModel::Errors.new(self)
end
def assign_attributes(attributes)
attributes.each do |key, value|
setter = :"#{key}="
public_send(setter, value) if respond_to?(setter)
end
end
class << self
include Dry::Monads
def validate(contract, params)
outcome = contract.call(params)
new.assign_attributes(outcome.to_h)
end
end
and then I call it it with:
MyForm.validate(ValidationContract.new, params)