Method: Attrio::Types::Array.typecast

Defined in:
lib/attrio/types/array.rb

.typecast(value, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/attrio/types/array.rb', line 6

def self.typecast(value, options = {})
  begin
    array = (!value.is_a?(::Array) && value.respond_to?(:split)) ? value.split(options[:split]): Attrio::Helpers.to_a(value).flatten
    if options[:element].present?

      type = Attrio::AttributesParser.cast_type(self.element_type(options[:element]))
      options = self.element_options(options[:element])

      array.map! do |item|
        if type.respond_to?(:typecast) && type.respond_to?(:typecasted?)
          type.typecasted?(item) ? item : type.typecast(item, options)
        else
          type == Hash && item.is_a?(Hash) ? value : type.new(item)
        end
      end
    end

    array
  rescue ArgumentError => e
    nil
  end
end