Last active
November 21, 2016 14:53
-
-
Save skorth/f27079e34e17ea8b7e701c6481b1b2d8 to your computer and use it in GitHub Desktop.
Building a FormObject by using dry-rb.org
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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