Class: Objective::Filters::RootFilter

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

Constant Summary collapse

Options =
OpenStruct.new

Instance Attribute Summary

Attributes inherited from Objective::Filter

#key, #sub_filters

Instance Method Summary collapse

Methods inherited from Objective::Filter

#coerce_error, #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



44
45
46
47
48
49
# File 'lib/objective/filters/root_filter.rb', line 44

def coerce(raw)
  raw.each_with_object(OpenStruct.new) do |datum, result|
    raise_argument_error unless datum.respond_to?(:each_pair)
    datum.each_pair { |key, value| result[key] = value }
  end
end

#feed(*raw) ⇒ Object



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

def feed(*raw)
  result = OpenStruct.new
  result.raw = raw
  result.coerced = coerce(raw)

  inputs = {}
  errors = Objective::Errors::ErrorHash.new

  data = result.coerced
  sub_filters_hash.each_pair do |key, key_filter|
    datum = data.to_h[key]
    key_filter_result = key_filter.feed(datum)

    sub_data = key_filter_result.inputs
    sub_error = key_filter_result.errors

    if sub_error.nil?
      inputs[key] = sub_data
    else
      errors[key] = key_filter.handle_errors(sub_error)
    end
  end

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

#filter(&block) ⇒ Object



8
9
10
# File 'lib/objective/filters/root_filter.rb', line 8

def filter(&block)
  instance_eval(&block)
end

#keysObject



12
13
14
# File 'lib/objective/filters/root_filter.rb', line 12

def keys
  sub_filters.map(&:key)
end

#raise_argument_errorObject

Raises:

  • (ArgumentError)


51
52
53
# File 'lib/objective/filters/root_filter.rb', line 51

def raise_argument_error
  raise(ArgumentError, 'All Objective arguments must be a Hash or OpenStruct')
end