-
Notifications
You must be signed in to change notification settings - Fork 136
/
base.rb
286 lines (244 loc) · 8.04 KB
/
base.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# coding: utf-8
# frozen_string_literal: true
require 'active_support/core_ext/hash/indifferent_access'
require 'set'
module ActiveInteraction
# @abstract Subclass and override {#execute} to implement a custom
# ActiveInteraction::Base class.
#
# Provides interaction functionality. Subclass this to create an interaction.
#
# @example
# class ExampleInteraction < ActiveInteraction::Base
# # Required
# boolean :a
#
# # Optional
# boolean :b, default: false
#
# def execute
# a && b
# end
# end
#
# outcome = ExampleInteraction.run(a: true)
# if outcome.valid?
# outcome.result
# else
# outcome.errors
# end
class Base
include ActiveModelable
include ActiveRecordable
include Runnable
define_callbacks :type_check
class << self
include Hashable
include Missable
# @!method run(inputs = {})
# @note If the interaction inputs are valid and there are no runtime
# errors and execution completed successfully, {#valid?} will always
# return true.
#
# Runs validations and if there are no errors it will call {#execute}.
#
# @param (see ActiveInteraction::Base#initialize)
#
# @return [Base]
# @!method run!(inputs = {})
# Like {.run} except that it returns the value of {#execute} or raises
# an exception if there were any validation errors.
#
# @param (see ActiveInteraction::Base.run)
#
# @return (see ActiveInteraction::Runnable::ClassMethods#run!)
#
# @raise (see ActiveInteraction::Runnable::ClassMethods#run!)
# Get or set the description.
#
# @example
# core.desc
# # => nil
# core.desc('Description!')
# core.desc
# # => "Description!"
#
# @param desc [String, nil] What to set the description to.
#
# @return [String, nil] The description.
def desc(desc = nil)
if desc.nil?
unless instance_variable_defined?(:@_interaction_desc)
@_interaction_desc = nil
end
else
@_interaction_desc = desc
end
@_interaction_desc
end
# Get all the filters defined on this interaction.
#
# @return [Hash{Symbol => Filter}]
def filters
@_interaction_filters ||= {}
end
# @private
def method_missing(*args, &block) # rubocop:disable Style/MethodMissing
super do |klass, names, options|
raise InvalidFilterError, 'missing attribute name' if names.empty?
names.each { |name| add_filter(klass, name, options, &block) }
end
end
private
# @param klass [Class]
# @param name [Symbol]
# @param options [Hash]
def add_filter(klass, name, options, &block)
if InputProcessor.reserved?(name)
raise InvalidFilterError, %("#{name}" is a reserved name)
end
initialize_filter(klass.new(name, options, &block))
end
# Import filters from another interaction.
#
# @param klass [Class] The other interaction.
# @param options [Hash]
#
# @option options [Array<Symbol>, nil] :only Import only these filters.
# @option options [Array<Symbol>, nil] :except Import all filters except
# for these.
#
# @return (see .filters)
#
# @!visibility public
def import_filters(klass, options = {})
only = options[:only]
except = options[:except]
other_filters = klass.filters.dup
other_filters.select! { |k, _| [*only].include?(k) } if only
other_filters.reject! { |k, _| [*except].include?(k) } if except
other_filters.values.each { |filter| initialize_filter(filter) }
end
# @param klass [Class]
def inherited(klass)
klass.instance_variable_set(:@_interaction_filters, filters.dup)
super
end
# @param filter [Filter]
def initialize_filter(filter)
attribute = filter.name
if filters.key?(attribute)
warn "WARNING: Redefining #{name}##{attribute} filter"
end
filters[attribute] = filter
attr_accessor attribute
define_method("#{attribute}?") { !public_send(attribute).nil? }
eagerly_evaluate_default(filter)
end
# @param filter [Filter]
def eagerly_evaluate_default(filter)
default = filter.options[:default]
filter.default if default && !default.is_a?(Proc)
end
end
# @param inputs [Hash{Symbol => Object}] Attribute values to set.
#
# @private
def initialize(inputs = {})
inputs = normalize_inputs!(inputs)
process_inputs(inputs.symbolize_keys)
end
# @!method compose(other, inputs = {})
# Run another interaction and return its result. If the other interaction
# fails, halt execution.
#
# @param other (see ActiveInteraction::Runnable#compose)
# @param inputs (see ActiveInteraction::Base#initialize)
#
# @return (see ActiveInteraction::Base.run!)
# @!method execute
# @abstract
#
# Runs the business logic associated with the interaction. This method is
# only run when there are no validation errors. The return value is
# placed into {#result}.
#
# @raise (see ActiveInteraction::Runnable#execute)
# Returns the inputs provided to {.run} or {.run!} after being cast based
# on the filters in the class.
#
# @return [Hash{Symbol => Object}] All inputs passed to {.run} or {.run!}.
def inputs
self.class.filters.keys.each_with_object({}) do |name, h|
h[name] = public_send(name)
end
end
# Returns `true` if the given key was in the hash passed to {.run}.
# Otherwise returns `false`. Use this to figure out if an input was given,
# even if it was `nil`.
#
# @example
# class Example < ActiveInteraction::Base
# integer :x, default: nil
# def execute; given?(:x) end
# end
# Example.run!() # => false
# Example.run!(x: nil) # => true
# Example.run!(x: rand) # => true
#
# @param input [#to_sym]
#
# @return [Boolean]
#
# @since 2.1.0
def given?(input)
@_interaction_keys.include?(input.to_sym)
end
protected
def run_validations!
type_check
super if errors.empty?
end
private
# We want to allow both `Hash` objects and `ActionController::Parameters`
# objects. In Rails < 5, parameters are a subclass of hash and calling
# `#symbolize_keys` returns the entire hash, not just permitted values. In
# Rails >= 5, parameters are not a subclass of hash but calling
# `#to_unsafe_h` returns the entire hash.
def normalize_inputs!(inputs)
return inputs if inputs.is_a?(Hash)
parameters = 'ActionController::Parameters'
klass = parameters.safe_constantize
return inputs.to_unsafe_h if klass && inputs.is_a?(klass)
raise ArgumentError, "inputs must be a hash or #{parameters}"
end
# @param inputs [Hash{Symbol => Object}]
def process_inputs(inputs)
@_interaction_keys = inputs.keys.to_set & self.class.filters.keys
inputs.each do |key, value|
raise InvalidValueError, key.inspect if InputProcessor.reserved?(key)
populate_reader(key, value)
end
populate_filters(InputProcessor.process(inputs))
end
def populate_reader(key, value)
instance_variable_set("@#{key}", value) if respond_to?(key)
end
def populate_filters(inputs)
self.class.filters.each do |name, filter|
begin
public_send("#{name}=", filter.clean(inputs[name], self))
rescue InvalidValueError, MissingValueError, NoDefaultError
nil # #type_check will add errors if appropriate.
end
end
end
def type_check
run_callbacks(:type_check) do
Validation.validate(self, self.class.filters, inputs).each do |error|
errors.add(*error)
end
end
end
end
end