Sha256: e1653e3fb2eb782b1580607f4685663f82cbc24722afb8a824af93a7a545486c

Contents?: true

Size: 1.64 KB

Versions: 7

Compression:

Stored size: 1.64 KB

Contents

require 'virtus'
require 'active_support/concern'
require 'active_model'
require 'avromatic/model/configuration'
require 'avromatic/model/value_object'
require 'avromatic/model/configurable'
require 'avromatic/model/attributes'
require 'avromatic/model/serialization'

module Avromatic
  module Model

    # This class implements generating models from Avro schemas.
    class Builder

      attr_reader :mod, :config

      # For options see Avromatic::Model.build
      def self.model(**options)
        Class.new do
          include Avromatic::Model::Builder.new(**options).mod

          # Name is required for attribute validations on an anonymous class.
          def self.name
            super || (@name ||= config.avro_schema.name.classify)
          end
        end
      end

      # For options see Avromatic::Model.build
      def initialize(**options)
        @mod = Module.new
        @config = Avromatic::Model::Configuration.new(**options)
        define_included_method
      end

      def inclusions
        [
          ActiveModel::Validations,
          Virtus.value_object,
          Avromatic::Model::Configurable,
          Avromatic::Model::Attributes,
          Avromatic::Model::ValueObject,
          Avromatic::Model::Serialization
        ]
      end

      private

      def define_included_method
        with_builder do |builder|
          mod.define_singleton_method(:included) do |model_class|
            model_class.include(*builder.inclusions)
            model_class.config = builder.config
            model_class.add_avro_fields
          end
        end
      end

      def with_builder
        yield(self)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
avromatic-0.4.0 lib/avromatic/model/builder.rb
avromatic-0.3.0 lib/avromatic/model/builder.rb
avromatic-0.2.0 lib/avromatic/model/builder.rb
avromatic-0.1.2 lib/avromatic/model/builder.rb
avromatic-0.1.2.pre.rc0 lib/avromatic/model/builder.rb
avromatic-0.1.1 lib/avromatic/model/builder.rb
avromatic-0.1.0 lib/avromatic/model/builder.rb