Sha256: 923e4798398bc6cff1f9fda88b5be994033273ca4a375f9ab2f212b3081f470f

Contents?: true

Size: 1.24 KB

Versions: 5

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

require 'avromatic/model/types/abstract_type'

module Avromatic
  module Model
    module Types
      class EnumType < AbstractType
        VALUE_CLASSES = [::String].freeze
        INPUT_CLASSES = [::String, ::Symbol].freeze

        attr_reader :allowed_values

        def initialize(allowed_values)
          @allowed_values = allowed_values.to_set
        end

        def name
          "enum#{allowed_values.to_a}"
        end

        def value_classes
          VALUE_CLASSES
        end

        def input_classes
          INPUT_CLASSES
        end

        def coerce(input)
          if input.nil?
            input
          elsif coercible?(input)
            input.to_s
          else
            raise ArgumentError.new("Could not coerce '#{input.inspect}' to #{name}")
          end
        end

        def coerced?(input)
          input.nil? || (input.is_a?(::String) && allowed_values.include?(input))
        end

        def coercible?(input)
          input.nil? ||
            (input.is_a?(::String) && allowed_values.include?(input)) ||
            (input.is_a?(::Symbol) && allowed_values.include?(input.to_s))
        end

        def serialize(value, **)
          value
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
avromatic-2.2.1 lib/avromatic/model/types/enum_type.rb
avromatic-2.2.0 lib/avromatic/model/types/enum_type.rb
avromatic-2.1.0 lib/avromatic/model/types/enum_type.rb
avromatic-2.0.1 lib/avromatic/model/types/enum_type.rb
avromatic-2.0.0 lib/avromatic/model/types/enum_type.rb