Sha256: b5032f0d7b9764e68f024f579812849e49f683b3a03d8da422066c164ade75a9

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

module AdequateJson
  class Base
    include Resolver
    include Jsonizer

    def initialize(model, json = nil, variant: nil)
      @model = model
      @variant = variant
      @json = json
    end

    def to_builder
      variant = @variant || :default
      builder = self.class.builders[variant]
      raise "Unknown serializer variant #{variant} for #{self.class.name}" if builder.nil?

      yield_builder builder
    end

    protected

    def yield_builder(builder)
      if @json.nil?
        Jbuilder.new do |json|
          @json = json
          instance_exec json, @model, @variant, &builder
        end
      else
        instance_exec @json, @model, @variant, &builder
      end
    end

    def serialize(model, **options)
      return if model.nil?

      choose_serializer(model, **options).to_builder
    end

    class << self
      def builder(variant = nil, &block)
        builders[variant || :default] = block
      end

      def builders
        @builders ||= {}
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
adequate_json-0.1.0 lib/adequate_json/base.rb