|
5 | 5 | */
|
6 | 6 | package json.ext;
|
7 | 7 |
|
| 8 | +import json.ext.RuntimeInfo; |
| 9 | + |
8 | 10 | import org.jcodings.Encoding;
|
9 | 11 | import org.jcodings.specific.ASCIIEncoding;
|
10 | 12 | import org.jcodings.specific.USASCIIEncoding;
|
@@ -115,6 +117,11 @@ private static <T extends IRubyObject> Handler<? super T> getHandlerFor(Ruby run
|
115 | 117 | case HASH :
|
116 | 118 | if (Helpers.metaclass(object) != runtime.getHash()) break;
|
117 | 119 | return (Handler<T>) HASH_HANDLER;
|
| 120 | + case STRUCT : |
| 121 | + RuntimeInfo info = RuntimeInfo.forRuntime(runtime); |
| 122 | + RubyClass fragmentClass = info.jsonModule.get().getClass("Fragment"); |
| 123 | + if (Helpers.metaclass(object) != fragmentClass) break; |
| 124 | + return (Handler<T>) FRAGMENT_HANDLER; |
118 | 125 | }
|
119 | 126 | return GENERIC_HANDLER;
|
120 | 127 | }
|
@@ -481,6 +488,28 @@ static RubyString ensureValidEncoding(ThreadContext context, RubyString str) {
|
481 | 488 | static final Handler<IRubyObject> NIL_HANDLER =
|
482 | 489 | new KeywordHandler<>("null");
|
483 | 490 |
|
| 491 | + /** |
| 492 | + * The default handler (<code>Object#to_json</code>): coerces the object |
| 493 | + * to string using <code>#to_s</code>, and serializes that string. |
| 494 | + */ |
| 495 | + static final Handler<IRubyObject> FRAGMENT_HANDLER = |
| 496 | + new Handler<IRubyObject>() { |
| 497 | + @Override |
| 498 | + RubyString generateNew(ThreadContext context, Session session, IRubyObject object) { |
| 499 | + GeneratorState state = session.getState(context); |
| 500 | + IRubyObject result = object.callMethod(context, "to_json", state); |
| 501 | + if (result instanceof RubyString) return (RubyString)result; |
| 502 | + throw context.runtime.newTypeError("to_json must return a String"); |
| 503 | + } |
| 504 | + |
| 505 | + @Override |
| 506 | + void generate(ThreadContext context, Session session, IRubyObject object, OutputStream buffer) throws IOException { |
| 507 | + RubyString result = generateNew(context, session, object); |
| 508 | + ByteList bytes = result.getByteList(); |
| 509 | + buffer.write(bytes.unsafeBytes(), bytes.begin(), bytes.length()); |
| 510 | + } |
| 511 | + }; |
| 512 | + |
484 | 513 | /**
|
485 | 514 | * The default handler (<code>Object#to_json</code>): coerces the object
|
486 | 515 | * to string using <code>#to_s</code>, and serializes that string.
|
|
0 commit comments