lib/basic_serializer.rb in basic_serializer-0.1.1 vs lib/basic_serializer.rb in basic_serializer-0.1.2

- old
+ new

@@ -1,66 +1,51 @@ # frozen_string_literal: true -# class UserSerializer < BasicSerializer -# attribute :id, :integer -# attribute :name, :string -# attribute :email, :string -# end - require "oj" +require "yaml" +require "basic_serializer/dsl" BasicStruct = Class.new(Struct) class BasicSerializer - VERSION = "0.1.0" + extend DSL - class << self - def attributes - @attributes ||= {} - end - - def attribute(name, type) - attributes[name] = type - - return if method_defined?(name) - - define_method(name) { object.send(name) } - end - - def model_name(name) - @model_name ||= name - end - - def custom_model_name - @model_name || name.gsub("Serializer", "") - end - - def schema_ref(ref) - @schema_ref ||= ref - end - end - attr_reader :object def initialize(object) @object = object.is_a?(Hash) ? struct(object) : object + remove_instance_variable(:@struct) if defined?(@struct) end - def as_json + def stringified_attributes hash = {} self.class.attributes.each_key do |attr_name| hash[attr_name] = send(attr_name) end - hash.transform_keys(&:to_s) + deep_stringify_keys(hash) end + alias as_json stringified_attributes + def to_json(*_args) - Oj.dump(as_json) + Oj.dump(stringified_attributes) end + def to_yaml + YAML.dump(stringified_attributes) + end + + def serialize + case self.class.instance_variable_get(:@format) + when :json then to_json + when :yaml then to_yaml + else stringified_attributes + end + end + def self.swagger_ref @schema_ref || "#/components/schemas/#{custom_model_name}" end def self.swagger_schema @@ -78,9 +63,19 @@ 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 ||= BasicStruct.new(*object.keys.map(&:to_sym), keyword_init: true)