Skip to content

Instantly share code, notes, and snippets.

@jeremyevans
Created February 4, 2021 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyevans/642c4365521b3ec5c9a52177a3ce3b43 to your computer and use it in GitHub Desktop.
Save jeremyevans/642c4365521b3ec5c9a52177a3ce3b43 to your computer and use it in GitHub Desktop.
diff --git a/lib/sequel/plugins/json_serializer.rb b/lib/sequel/plugins/json_serializer.rb
index 510923dbd..1e62bdc4c 100644
--- a/lib/sequel/plugins/json_serializer.rb
+++ b/lib/sequel/plugins/json_serializer.rb
@@ -133,10 +133,8 @@ module Sequel
end
end
- # Helper class used for making sure that cascading options
- # for model associations works correctly. Cascaded options
- # work by creating instances of this class, which take a
- # literal JSON string and have +to_json+ return it.
+ # SEQUEL6: Remove
+ # :nocov:
class Literal
# Store the literal JSON to use
def initialize(json)
@@ -148,6 +146,20 @@ module Sequel
@json
end
end
+ # :nocov:
+ Sequel::Deprecation.deprecate_constant(self, :Literal)
+
+ def self.as_json(obj, *v, &block)
+ if obj.is_a?(Array)
+ obj.map{|x| as_json(x, *v, &block)}
+ else
+ if obj.respond_to?(:as_json)
+ obj.as_json(*v, &block)
+ else
+ JSON.parse(Sequel.object_to_json(obj, *v, &block))
+ end
+ end
+ end
module ClassMethods
# The default opts to use when serializing model objects to JSON.
@@ -324,20 +336,7 @@ module Sequel
end
v = v.empty? ? [] : [v]
-
- objs = public_send(k)
-
- is_array = if r = model.association_reflection(k)
- r.returns_array?
- else
- objs.is_a?(Array)
- end
-
- h[key_name] = if is_array
- objs.map{|obj| Literal.new(Sequel.object_to_json(obj, *v))}
- else
- Literal.new(Sequel.object_to_json(objs, *v))
- end
+ h[key_name] = JsonSerializer.as_json(public_send(k), *v)
end
else
Array(inc).each do |c|
@@ -347,7 +346,8 @@ module Sequel
else
key_name = c.to_s
end
- h[key_name] = public_send(c)
+
+ h[key_name] = JsonSerializer.as_json(public_send(c))
end
end
end
@@ -362,6 +362,14 @@ module Sequel
h = yield h if block_given?
Sequel.object_to_json(h, *a)
end
+
+ def as_json(*v, &block)
+ if block
+ to_json(*v){|x| return block.call(x)}
+ else
+ to_json(*v){|x| return x}
+ end
+ end
end
module DatasetMethods
@@ -420,7 +428,7 @@ module Sequel
else
all
end
- array.map{|obj| Literal.new(Sequel.object_to_json(obj, opts, &opts[:instance_block]))}
+ JsonSerializer.as_json(array, opts, &opts[:instance_block])
else
all
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment