Sha256: 86ca354da3654c6589a899948a98f2ea3e8eb8ace7ec4a7b9341e3aa62535b20

Contents?: true

Size: 1.31 KB

Versions: 3

Compression:

Stored size: 1.31 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

        def referenced_model_classes
          EMPTY_ARRAY
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
avromatic-2.2.4 lib/avromatic/model/types/enum_type.rb
avromatic-2.2.3 lib/avromatic/model/types/enum_type.rb
avromatic-2.2.2 lib/avromatic/model/types/enum_type.rb