Module: Attributor::Container::ClassMethods

Defined in:
lib/attributor/types/container.rb

Instance Method Summary collapse

Instance Method Details

#decode_json(value, context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Array

Decode JSON string that encapsulates an array

Parameters:

  • value (String)

    JSON string

Returns:

  • (Array)

    a normal Ruby Array


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/attributor/types/container.rb', line 22

def decode_json(value, context=Attributor::DEFAULT_ROOT_CONTEXT)
  raise Attributor::DeserializationError, context: context, from: value.class, encoding: "JSON" , value: value unless value.kind_of? ::String

  # attempt to parse as JSON
  parsed_value = JSON.parse(value)

  if self.valid_type?(parsed_value)
    value = parsed_value
  else
    raise Attributor::CoercionError, context: context, from: parsed_value.class, to: self.name, value: parsed_value
  end
  return value

rescue JSON::JSONError => e
  raise Attributor::DeserializationError, context: context, from: value.class, encoding: "JSON" , value: value
end

#decode_string(value, context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Object


13
14
15
# File 'lib/attributor/types/container.rb', line 13

def decode_string(value, context=Attributor::DEFAULT_ROOT_CONTEXT)
  raise "#{self.name}.decode_string is not implemented. (when decoding #{Attributor.humanize_context(context)})"
end