Module: Mongoid::MultiParameterAttributes

Defined in:
lib/mongoid/multi_parameter_attributes.rb

Overview

@todo: Durran: This module needs an overhaul.

Defined Under Namespace

Modules: Errors

Instance Method Summary collapse

Instance Method Details

#process(attrs = nil, guard_protected_attributes = true) ⇒ Object



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
# File 'lib/mongoid/multi_parameter_attributes.rb', line 30

def process(attrs = nil, guard_protected_attributes = true)
  if attrs
    errors = []
    attributes = {}
    multi_parameter_attributes = {}

    attrs.each_pair do |key, value|
      if key =~ /^([^\(]+)\((\d+)([if])\)$/
        key, index = $1, $2.to_i
        (multi_parameter_attributes[key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}")
      else
        attributes[key] = value
      end
    end

    multi_parameter_attributes.each_pair do |key, values|
      begin
        values = (values.keys.min..values.keys.max).map { |i| values[i] }
        klass = self.class.fields[key].try(:type)
        attributes[key] = instantiate_object(klass, values)
      rescue => e
        errors << Errors::AttributeAssignmentError.new("error on assignment #{values.inspect} to #{key}", e, key)
      end
    end

    unless errors.empty?
      raise Errors::MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
    end

    super attributes, guard_protected_attributes
  else
    super
  end
end