Sha256: 589c4a1db23652312fb03afbf107e73011488359e1cc89ae61e3e287d774987d

Contents?: true

Size: 1 KB

Versions: 4

Compression:

Stored size: 1 KB

Contents

module Rasti
  module Types
    class Hash

      include Castable

      attr_reader :key_type, :value_type

      def self.[](key_type, value_type)
        new key_type, value_type
      end

      def to_s
        "#{self.class}[#{key_type}, #{value_type}]"
      end
      alias_method :inspect, :to_s

      private

      def initialize(key_type, value_type)
        @key_type = key_type
        @value_type = value_type
      end

      def valid?(value)
        value.is_a? ::Hash
      end

      def transform(value)
        result = {}
        errors = {}

        value.each do |k,v|
          begin
            result[key_type.cast k] = value_type.cast v

          rescue CompoundError => ex
            ex.errors.each do |key, messages|
              errors["#{k}.#{key}"] = messages
            end

          rescue => error
            errors[k] = [error.message]
          end
        end

        raise MultiCastError.new(self, value, errors) unless errors.empty?

        result
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rasti-types-1.1.2 lib/rasti/types/hash.rb
rasti-types-1.1.1 lib/rasti/types/hash.rb
rasti-types-1.1.0 lib/rasti/types/hash.rb
rasti-types-1.0.0 lib/rasti/types/hash.rb