Skip to content

Instantly share code, notes, and snippets.

@scottserok
Created April 14, 2021 07:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottserok/872f44c6066150e74e097756a0331eb9 to your computer and use it in GitHub Desktop.
Save scottserok/872f44c6066150e74e097756a0331eb9 to your computer and use it in GitHub Desktop.
A module that combines dry-initializer and dry-schema
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