-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathstruct.rb
50 lines (40 loc) · 1.23 KB
/
struct.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
require "dry/struct"
module Dry
module Schema
module Macros
class StructToSchema < ::Dry::Struct::Compiler
def call(struct)
visit(struct.to_ast)
end
# strip away structs from AST
def visit_struct(node)
_, ast = node
visit(ast)
end
end
Hash.option :struct_compiler, default: proc { StructToSchema.new(schema_dsl.config.types) }
Hash.prepend(::Module.new {
def call(*args)
if args.size >= 1 && struct?(args[0])
if block_given?
raise ArgumentError, "blocks are not supported when using " \
"a struct class (#{name.inspect} => #{args[0]})"
end
schema = struct_compiler.(args[0])
super(schema, *args.drop(1))
type(schema_dsl.types[name].constructor(schema))
else
super
end
end
private
def struct?(type)
type.is_a?(::Class) && type <= ::Dry::Struct
end
})
end
PredicateInferrer::Compiler.alias_method(:visit_struct, :visit_hash)
PrimitiveInferrer::Compiler.alias_method(:visit_struct, :visit_hash)
end
end