Skip to content

Instantly share code, notes, and snippets.

@skorth
Last active November 21, 2016 14:53
Show Gist options
  • Save skorth/f27079e34e17ea8b7e701c6481b1b2d8 to your computer and use it in GitHub Desktop.
Save skorth/f27079e34e17ea8b7e701c6481b1b2d8 to your computer and use it in GitHub Desktop.
Building a FormObject by using dry-rb.org
class FooForm < Dry::Struct
constructor_type(:schema)
module Types
include Dry::Types.module
end
attribute :title, Types::Coercible::String
attribute :location, Types::Coercible::String
attribute :description, Types::Coercible::String
attribute :date, Types::Form::DateTime
def save
errors = Schema.call(to_hash).messages(full: true)
raise CommandValidationFailed, errors if errors.present?
MyModel.create!(to_hash)
return errors
end
private
Schema = Dry::Validation.Form do
configure do
config.messages_file = Rails.root.join('config/locales/errors.yml')
config.messages = :i18n
end
required(:title).filled(:str?)
required(:date).filled
required(:location).maybe(:str?)
required(:description).maybe(:str?)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment