Skip to content

Commit a3f6261

Browse files
committed
FileBlobs and AppendInputs
1 parent 6b1fff2 commit a3f6261

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

lib/active_interaction/extras.rb

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,86 @@ def all(params = {})
187187
end
188188
end
189189
end
190+
191+
192+
concerning :AppendInputs do
193+
module InputsRefinement
194+
refine ActiveInteraction::Inputs do
195+
# Based on ActiveInteraction::Inputs#initialize
196+
def append(raw_inputs, overwrite: false)
197+
new_normalized_inputs = normalize(raw_inputs)
198+
199+
keys = new_normalized_inputs.keys.map(&:to_sym)
200+
keys = keys.reject { given?(_1) } if !overwrite
201+
202+
new_inputs = @base.class.filters
203+
.slice(*keys)
204+
.each_with_object({}) do |(name, filter), inputs|
205+
inputs[name] = filter.process(new_normalized_inputs[name], @base)
206+
207+
yield(name, inputs[name]) if block_given?
208+
end
209+
210+
@normalized_inputs = @normalized_inputs.merge(new_normalized_inputs)
211+
@inputs = @inputs.merge(new_inputs)
212+
@to_h = nil
213+
end
214+
end
215+
end
216+
217+
using InputsRefinement
218+
219+
def default_inputs(*args)
220+
inputs.append(*args) do |name, input|
221+
public_send("#{name}=", input.value)
222+
end
223+
end
224+
225+
# def default_input(name, &block)
226+
# if !inputs.given?(name)
227+
# default_inputs(name: block.call)
228+
# end
229+
# end
230+
231+
class_methods do
232+
def default_inputs(&block)
233+
after_initialize do
234+
hash = block.call
235+
default_inputs(hash)
236+
end
237+
end
238+
239+
def default_input(name, &block)
240+
after_initialize do
241+
default_inputs(name => instance_exec(&block))
242+
end
243+
end
244+
end
245+
end
246+
247+
concerning :FileBlobs do
248+
def blobs_for(array_field)
249+
# If there is a new upload field, prioritize it
250+
new_upload = "new_#{array_field}"
251+
if respond_to?(new_upload) && public_send(new_upload).present?
252+
array_field = new_upload
253+
end
254+
255+
list = public_send(array_field)
256+
list = Array.wrap(list)
257+
258+
list.compact_blank.map do |file|
259+
case file
260+
when ActiveStorage::Blob
261+
file
262+
when ActiveStorage::Attachment, ActiveStorage::Attached::One
263+
file.blob
264+
when String
265+
ActiveStorage::Blob.find_signed(file)
266+
end
267+
end.compact
268+
end
269+
end
190270
end
191271
end
192272

0 commit comments

Comments
 (0)