Class: Objective::Filters::ArrayFilter

Inherits:
Objective::Filter show all
Defined in:
lib/objective/filters/array_filter.rb

Instance Attribute Summary

Attributes inherited from Objective::Filter

#key, #sub_filters

Instance Method Summary collapse

Methods inherited from Objective::Filter

#default, #default?, #dup, #feed_empty, #feed_invalid, #feed_nil, #feed_none, #feed_result, filter_name, #handle_errors, inherited, #initialize, #options, #sub_filters_hash, #type_specific_options_hash, #validate

Constructor Details

This class inherits a constructor from Objective::Filter

Instance Method Details

#coerce(raw) ⇒ Object



39
40
41
42
# File 'lib/objective/filters/array_filter.rb', line 39

def coerce(raw)
  return Array.wrap(raw) if options.wrap
  raw
end

#coerce_error(coerced) ⇒ Object



44
45
46
# File 'lib/objective/filters/array_filter.rb', line 44

def coerce_error(coerced)
  return :array unless coerced.is_a?(Array)
end

#feed(raw) ⇒ Object



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
# File 'lib/objective/filters/array_filter.rb', line 5

def feed(raw)
  result = super(raw)
  return result if result == Objective::DISCARD || result.errors || result.inputs.nil?

  inputs = []
  errors = Objective::Errors::ErrorArray.new

  sub_filter = sub_filters.first

  index_shift = 0

  data = result.coerced
  data.each_with_index do |sub_data, index|
    sub_result = sub_filter.feed(sub_data)
    if sub_result == Objective::DISCARD
      index_shift += 1
      next
    end

    sub_data = sub_result.inputs
    sub_error = sub_result.errors

    unless sub_error.nil?
      errors[index - index_shift] = sub_filter.handle_errors(sub_error)
    end

    inputs[index - index_shift] = sub_data
  end

  result.inputs = inputs
  result.errors = errors.present? ? errors : nil
  result
end