lib/basic_serializer.rb in basic_serializer-0.1.5 vs lib/basic_serializer.rb in basic_serializer-0.1.6
- old
+ new
@@ -4,30 +4,27 @@
require "yaml"
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.is_a?(Hash) ? struct(object) : object
+ @object = object
+
+ @object = @object.is_a?(::Hash) ? struct : @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)
+ hash.deep_stringify_keys
end
alias as_json stringified_attributes
def to_json(*_args)
@@ -51,20 +48,20 @@
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
+ 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(object)
+ def struct
return @struct if @struct
basic_struct ||= BasicSerializer::Struct.new(*object.keys.map(&:to_sym), keyword_init: true)
@struct ||= basic_struct.new(**object)