-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclass_interface.rb
More file actions
115 lines (104 loc) · 2.94 KB
/
Copy pathclass_interface.rb
File metadata and controls
115 lines (104 loc) · 2.94 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# frozen_string_literal: true
require 'dry/transformer/pipe/dsl'
module Dry
module Transformer
class Pipe
# @api public
module ClassInterface
# @api private
attr_reader :dsl
# Return a base Dry::Transformer class with the
# container configured to the passed argument.
#
# @example
#
# class MyTransformer < Dry::Transformer[Transproc]
# end
#
# @param [Transproc::Registry] container
# The container to resolve transprocs from
#
# @return [subclass of Dry::Transformer]
#
# @api public
def [](container)
klass = Class.new(self)
klass.container(container)
klass
end
# @api private
def inherited(subclass)
super
subclass.container(@container) if defined?(@container)
subclass.instance_variable_set('@dsl', dsl.dup) if dsl
end
# Get or set the container to resolve transprocs from.
#
# @example
#
# # Setter
# Dry::Transformer.container(Transproc)
# # => Transproc
#
# # Getter
# Dry::Transformer.container
# # => Transproc
#
# @param [Transproc::Registry] container
# The container to resolve transprocs from
#
# @return [Transproc::Registry]
#
# @api private
def container(container = Undefined)
if container.equal?(Undefined)
@container ||= Module.new.extend(Dry::Transformer::Registry)
else
@container = container
end
end
# @api public
def import(*args)
container.import(*args)
end
# @api public
def define!(&block)
@dsl ||= DSL.new(container)
@dsl.instance_eval(&block)
self
end
# @api public
def new(*)
super.tap do |transformer|
transformer.instance_variable_set('@transproc', dsl.(transformer)) if dsl
end
end
ruby2_keywords(:new) if respond_to?(:ruby2_keywords, true)
# Get a transformation from the container,
# without adding it to the transformation pipeline
#
# @example
#
# class Stringify < Dry::Transformer
# map_values t(:to_string)
# end
#
# Stringify.new.call(a: 1, b: 2)
# # => {a: '1', b: '2'}
#
# @param [Proc, Symbol] fn
# A proc, a name of the module's own function, or a name of imported
# procedure from another module
# @param [Object, Array] args
# Args to be carried by the transproc
#
# @return [Transproc::Function]
#
# @api public
def t(fn, *args, **kwargs)
container[fn, *args, **kwargs]
end
end
end
end
end