# frozen_string_literal: true require "oj" require "yaml" require "basic_serializer/dsl" require "basic_serializer/swagger" require "basic_serializer/struct" require "basic_serializer/config" class BasicSerializer extend DSL extend Swagger attr_reader :object def initialize(object) @object = object.is_a?(Hash) ? struct(object) : object remove_instance_variable(:@struct) if defined?(@struct) end def stringified_attributes hash = {} self.class.attributes.each_key do |attr_name| hash[attr_name] = send(attr_name) end deep_stringify_keys(hash) end alias as_json stringified_attributes def to_json(*_args) pretty = self.class.instance_variable_get(:@format)&.dig(:pretty) Oj.dump(stringified_attributes, **(pretty ? Config::OJ_FORMAT : {})) end def to_yaml YAML.dump(stringified_attributes) end def serialize case self.class.instance_variable_get(:@format)&.dig(:name) when :json then to_json when :yaml then to_yaml else stringified_attributes end end singleton_class.alias_method :openapi_ref, :swagger_ref singleton_class.alias_method :openapi_schema, :swagger_schema private def deep_stringify_keys(hash) hash.transform_keys(&:to_s).transform_values do |value| case value when Hash then deep_stringify_keys(value) when Array then value.map { |item| item.is_a?(Hash) ? deep_stringify_keys(item) : item } else value end end end def struct(object) return @struct if @struct basic_struct ||= BasicSerializer::Struct.new(*object.keys.map(&:to_sym), keyword_init: true) @struct ||= basic_struct.new(**object) end end