Sha256: 6e2261d53587bc3a19cf6473317854bf9b8dd2454cade3389a1e154d105c5805

Contents?: true

Size: 1.28 KB

Versions: 14

Compression:

Stored size: 1.28 KB

Contents

module Attributor
  module Container
    # Module for types that can contain subtypes. Collection.of(?) or Hash.of(?)
    def self.included(klass)
      klass.module_eval do
        include Attributor::Type
      end
      klass.extend(ClassMethods)
    end

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

      # Decode JSON string that encapsulates an array
      #
      # @param value [String] JSON string
      # @return [Array] a normal Ruby Array
      #
      def decode_json(value, context = Attributor::DEFAULT_ROOT_CONTEXT)
        raise Attributor::DeserializationError.new(context: context, from: value.class, encoding: 'JSON', value: value) unless value.is_a? ::String

        # attempt to parse as JSON
        parsed_value = JSON.parse(value)
        unless valid_type?(parsed_value)
          raise Attributor::CoercionError.new(context: context, from: parsed_value.class, to: name, value: parsed_value)
        end

        parsed_value
      rescue JSON::JSONError
        raise Attributor::DeserializationError.new(context: context, from: value.class, encoding: 'JSON', value: value)
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
attributor-8.0 lib/attributor/types/container.rb
attributor-7.1 lib/attributor/types/container.rb
attributor-7.0 lib/attributor/types/container.rb
attributor-6.5 lib/attributor/types/container.rb
attributor-6.4 lib/attributor/types/container.rb
attributor-6.3 lib/attributor/types/container.rb
attributor-6.2 lib/attributor/types/container.rb
attributor-6.1 lib/attributor/types/container.rb
attributor-6.0 lib/attributor/types/container.rb
attributor-5.7 lib/attributor/types/container.rb
attributor-5.6 lib/attributor/types/container.rb
attributor-5.5 lib/attributor/types/container.rb
attributor-5.4 lib/attributor/types/container.rb
attributor-5.3 lib/attributor/types/container.rb