Sha256: 3ed884af21796dbe87bb0b4725e4bcdfb1d14c6fb421880b60023b2186ebafe9

Contents?: true

Size: 1.6 KB

Versions: 58

Compression:

Stored size: 1.6 KB

Contents

require 'avromatic/model/null_custom_type'

module Avromatic
  module Model

    # Instances of this class contains the configuration for custom handling of
    # a named type (record, enum, fixed).
    class CustomType

      attr_accessor :to_avro, :from_avro, :value_class

      def initialize(value_class)
        @value_class = value_class
      end

      # A deserializer method is used when assigning to the model. It is used both when
      # deserializing a model instance from Avro and when directly instantiating
      # an instance. The deserializer method must accept a single argument and return
      # the value to store in the model for the attribute.
      def deserializer
        proc = from_avro_proc
        wrap_proc(proc) if proc
      end

      # A serializer method is used when preparing attributes to be serialized using
      # Avro. The serializer method must accept a single argument of the model value
      # for the attribute and return a value in a form that Avro can serialize
      # for the attribute.
      def serializer
        proc = to_avro_proc
        wrap_proc(proc) if proc
      end

      private

      def to_avro_proc
        to_avro || value_class_method(:to_avro)
      end

      def from_avro_proc
        from_avro || value_class_method(:from_avro)
      end

      def value_class_method(method_name)
        value_class && value_class.respond_to?(method_name) &&
          value_class.method(method_name).to_proc
      end

      # Wrap the supplied Proc to handle nil.
      def wrap_proc(proc)
        ->(value) { proc.call(value) if value }
      end
    end
  end
end

Version data entries

58 entries across 58 versions & 1 rubygems

Version Path
avromatic-1.0.0 lib/avromatic/model/custom_type.rb
avromatic-0.33.0 lib/avromatic/model/custom_type.rb
avromatic-0.32.0 lib/avromatic/model/custom_type.rb
avromatic-0.32.0.rc0 lib/avromatic/model/custom_type.rb
avromatic-0.31.0 lib/avromatic/model/custom_type.rb
avromatic-0.30.0 lib/avromatic/model/custom_type.rb
avromatic-0.29.1 lib/avromatic/model/custom_type.rb
avromatic-0.29.0 lib/avromatic/model/custom_type.rb
avromatic-0.28.1 lib/avromatic/model/custom_type.rb
avromatic-0.27.0 lib/avromatic/model/custom_type.rb
avromatic-0.26.0 lib/avromatic/model/custom_type.rb
avromatic-0.25.0 lib/avromatic/model/custom_type.rb
avromatic-0.24.0 lib/avromatic/model/custom_type.rb
avromatic-0.23.0 lib/avromatic/model/custom_type.rb
avromatic-0.22.0 lib/avromatic/model/custom_type.rb
avromatic-0.21.1 lib/avromatic/model/custom_type.rb
avromatic-0.21.0 lib/avromatic/model/custom_type.rb
avromatic-0.21.0.rc1 lib/avromatic/model/custom_type.rb
avromatic-0.21.0.rc0 lib/avromatic/model/custom_type.rb
avromatic-0.20.0 lib/avromatic/model/custom_type.rb