lib/json_serializer.rb in json-serializer-0.0.9 vs lib/json_serializer.rb in json-serializer-1.0.0
- old
+ new
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
require "json"
class JsonSerializer
module Utils
def self.const(context, name)
@@ -23,39 +25,43 @@
def self.attributes
@attributes ||= {}
end
- attr :object
+ attr_reader :object
def initialize(object)
@object = object
end
- def to_json(options={})
- if root = options[:root]
- { root => serializable_object }.to_json
- else
- serializable_object.to_json
- end
+ def to_json(root: nil)
+ result = decorate
+ result = { root => result } if root
+
+ result.to_json
end
- protected
+ def decorate
+ return nil unless object
- def serializable_object
- return nil unless @object
-
- if @object.respond_to?(:to_a)
- @object.to_a.map { |item| self.class.new(item).to_hash }
+ if object.respond_to?(:to_a)
+ to_arry
else
to_hash
end
end
+ protected
+
+ def to_arry
+ object.to_a.map { |o| self.class.new(o).to_hash }
+ end
+
def to_hash
self.class.attributes.each_with_object({}) do |(name, serializer), hash|
- data = self.class.method_defined?(name) ? self.send(name) : @object.send(name)
- data = Utils.const(self.class, serializer).new(data).serializable_object if serializer
- hash[name] = data
+ res = self.class.method_defined?(name) ? send(name) : object.send(name)
+ res = Utils.const(self.class, serializer).new(res).decorate if serializer
+
+ hash[name] = res
end
end
end