Class: Objective::Filters::ArrayFilter

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

Constant Summary collapse

Options =
OpenStruct.new(
  nils: Objective::DENY,
  invalid: Objective::DENY,
  strict: false,
  wrap: false
)

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_result, #handle_errors, inherited, #initialize, #options, #sub_filters_hash, #validate

Constructor Details

This class inherits a constructor from Objective::Filter

Instance Method Details

#coerce(raw) ⇒ Object



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

def coerce(raw)
  return Objective::Helpers.wrap(raw) if options.wrap
  raw
end

#coerce_error(coerced) ⇒ Object



47
48
49
# File 'lib/objective/filters/array_filter.rb', line 47

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

#feed(raw) ⇒ Object



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

def feed(raw)
  result = super(raw)
  return result if 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)
    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.empty? ? nil : errors
  result
end