Sha256: b36f530ae1c6f979b256a40c256483ecb396c87779837d0fe28314f967205dfd

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

require "oj"
require "yaml"
require "set"
require "basic_serializer/dsl"
require "basic_serializer/swagger"
require "basic_serializer/struct"
require "basic_serializer/config"
require "basic_serializer/hash"
class BasicSerializer
  extend DSL
  extend Swagger

  attr_reader :object

  def initialize(object)
    @object = object

    @object = @object.is_a?(::Hash) ? struct : @object

    remove_instance_variable(:@struct) if defined?(@struct)
  end

  def stringified_attributes
    hash.deep_stringify_keys
  end

  alias as_json stringified_attributes

  def to_json(*_args)
    Oj.dump(stringified_attributes, **json_format_options)
  end

  def to_yaml
    YAML.dump(stringified_attributes)
  end

  def serialize
    case self.class.format_settings[: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 hash
    @hash ||= BasicSerializer::Hash.new

    self.class.attributes.each_key do |attr_name|
      @hash[attr_name] = send(attr_name)
    end

    @hash
  end

  def struct
    return @struct if @struct

    basic_struct ||= BasicSerializer::Struct.new(*object.keys.map(&:to_sym), keyword_init: true)

    @struct ||= basic_struct.new(**object)
  end

  def json_format_options
    @json_format_options ||= self.class.format_settings[:pretty] ? Config::OJ_FORMAT : {}
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
basic_serializer-0.1.8 lib/basic_serializer.rb