Module: Virtus::Multiparams::AttributeSetExtension

Defined in:
lib/virtus/multiparams.rb

Instance Method Summary collapse

Instance Method Details

#coerce(attributes) ⇒ Object



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
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/virtus/multiparams.rb', line 11

def coerce(attributes)
  super(attributes).tap do |attributes|
    multiparams = Hash.new { |hash, key| hash[key] = {} }

    attributes.each do |(key, value)|
      if /\A(?<name>.+)\((?<offset>[0-9]+)(?<cast>[if])?\)\Z/ =~ key
        attributes.delete(key)

        unless attributes.include? name
          offset = offset.to_i
          value = value.send("to_#{cast}") if cast
          multiparams[name][offset] = value
        end
      end
    end

    multiparams.each do |name, values|
      array = Array.new(values.keys.max)

      values.each do |offset, value|
        array[offset - 1] = value
      end

      # Virus::Attribute has a primitive type which might be Date, Time, DateTime, etc.
      attribute = self[name]

      attributes[name] =
        if attribute.primitive <= Date || attribute.primitive <= Time
          # Basic convesion is enough, Virtus invokes `to_date[time]`
          # Also, lololol timezones
          if array.length >= 3 && array[0...3].none?(&:nil?) && array[0...3].none?(&:zero?)
            Time.new(*array[0...6])
          end
        else
          array
        end
    end
  end
end