Sha256: 2938e32603d7f5c0918fd867ba305c44af7e2a2a800294ad33e675b97e517683

Contents?: true

Size: 2 KB

Versions: 1

Compression:

Stored size: 2 KB

Contents

module AxleAttributes::Serializations::Builder
  class Serialization
    attr_accessor :model, :reflection
    def initialize(model, reflection)
      @model = model
      @reflection = reflection
    end

    def build!
      model.serialization_reflections = model.serialization_reflections.merge(reflection.name => reflection)

      define_attributes
      define_writer
      define_reader
    end

    def define_attributes
      model.attribute_definition_class.new(model, reflection.storage_column, type: :json, index: false, version: true).setup!

      model.has_attributes(meta_attributes)

      setup_definitions_on_parent
    end

    def mixin
      model.generated_serialized_object_methods
    end

    def define_writer
      name = reflection.name

      mixin.redefine_method "#{name}=" do |records|
        child_serialization(name).writer(records)
      end

      mixin.redefine_method "#{name}_attributes=" do |attrs|
        child_serialization(name).attributes_writer(attrs)
      end
    end

    def define_reader
      name = reflection.name

      mixin.redefine_method(name) do
        child_serialization(name).reader
      end

      mixin.redefine_method("#{name}_was") do
        child_serialization(name).reader_was
      end
    end

    def setup_definitions_on_parent
      serialized_index_mapping = {
        type: index_type,
        properties: {}
      }

      reflection.klass.attributes.each_value do |definition|
        definition.nested_path = reflection.name.to_s if reflection.collection?

        model.add_attribute_definition("#{reflection.name}.#{definition.name}", definition)

        if mapping = definition.index_mapping
          serialized_index_mapping[:properties][definition.name] = mapping
        end
      end

      model.elastic_index.mapping[:properties].merge!(reflection.name.to_s => serialized_index_mapping)
    end

    protected

      def index_type
        raise "index_type must be implemented"
      end

      def meta_attributes
        {}
      end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
axle_attributes-1.13.2 lib/axle_attributes/serializations/builder/serialization.rb