Created
April 14, 2021 07:47
-
-
Save scottserok/872f44c6066150e74e097756a0331eb9 to your computer and use it in GitHub Desktop.
A module that combines dry-initializer and dry-schema
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
require 'bundler/inline' | |
require 'json' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'dry-initializer' | |
gem 'dry-schema' | |
end | |
# class User | |
# include SchemaInitializer | |
# | |
# schema do | |
# required(:email).filled(:string) | |
# required(:name).maybe(:string) | |
# required(:is_admin).value(:bool?) | |
# end | |
# | |
# def to_s | |
# "EMAIL=#{email} NAME=#{name} ADMIN=#{is_admin}" | |
# end | |
# end | |
module SchemaInitializer | |
def self.included(mod) | |
mod.extend Dry::Initializer | |
mod.extend ClassMethods | |
end | |
module ClassMethods | |
def schema(&block) | |
@schema = Dry::Schema.Params do | |
instance_eval &block | |
end | |
instance_eval do | |
@schema.rules.keys.each do |attr| | |
option attr, optional: true | |
end | |
end | |
end | |
def process_kwargs(kwargs) | |
result = @schema.call(kwargs) | |
fail(ValidationError, result.errors.to_h.to_json) if result.failure? | |
result.to_h | |
end | |
def new(**kwargs) | |
super process_kwargs(kwargs) | |
end | |
end | |
ValidationError = Class.new(StandardError) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment