From 63df8d6f2c1181b329cd3fd4541434fea2b36036 Mon Sep 17 00:00:00 2001 From: Watson Date: Sun, 18 Aug 2024 22:28:38 +0900 Subject: [PATCH] Do not override Object#to_json with mimic_json --- ext/oj/mimic_json.c | 4 +++- ext/oj/oj.c | 7 +++++++ ext/oj/oj.h | 2 ++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/ext/oj/mimic_json.c b/ext/oj/mimic_json.c index 35ad0896..26b9ebdb 100644 --- a/ext/oj/mimic_json.c +++ b/ext/oj/mimic_json.c @@ -905,7 +905,9 @@ oj_define_mimic_json(int argc, VALUE *argv, VALUE self) { } oj_mimic_json_methods(json); - rb_define_method(rb_cObject, "to_json", mimic_object_to_json, -1); + if (!RTEST(rb_funcall2(rb_cObject, oj_method_defined_p_id, 1, &oj_to_json_sym))) { + rb_define_method(rb_cObject, "to_json", mimic_object_to_json, -1); + } rb_gv_set("$VERBOSE", verbose); diff --git a/ext/oj/oj.c b/ext/oj/oj.c index 8b3354ce..9b8dcc59 100644 --- a/ext/oj/oj.c +++ b/ext/oj/oj.c @@ -72,6 +72,7 @@ ID oj_utc_id; ID oj_utc_offset_id; ID oj_utcq_id; ID oj_write_id; +ID oj_method_defined_p_id; VALUE oj_bag_class; VALUE oj_bigdecimal_class; @@ -98,6 +99,7 @@ VALUE oj_quirks_mode_sym; VALUE oj_safe_sym; VALUE oj_symbolize_names_sym; VALUE oj_trace_sym; +VALUE oj_to_json_sym; static VALUE allow_blank_sym; static VALUE allow_gc_sym; @@ -1887,6 +1889,8 @@ void Init_oj(void) { oj_utcq_id = rb_intern("utc?"); oj_write_id = rb_intern("write"); + oj_method_defined_p_id = rb_intern("method_defined?"); + rb_require("oj/bag"); rb_require("oj/error"); rb_require("oj/mimic"); @@ -2061,6 +2065,9 @@ void Init_oj(void) { xss_safe_sym = ID2SYM(rb_intern("xss_safe")); rb_gc_register_address(&xss_safe_sym); + oj_to_json_sym = ID2SYM(oj_to_json_id); + rb_gc_register_address(&oj_to_json_sym); + oj_slash_string = rb_str_new2("/"); rb_gc_register_address(&oj_slash_string); OBJ_FREEZE(oj_slash_string); diff --git a/ext/oj/oj.h b/ext/oj/oj.h index f6ff51e6..5e61ad4c 100644 --- a/ext/oj/oj.h +++ b/ext/oj/oj.h @@ -323,6 +323,7 @@ extern VALUE oj_space_before_sym; extern VALUE oj_space_sym; extern VALUE oj_symbolize_names_sym; extern VALUE oj_trace_sym; +extern VALUE oj_to_json_sym; extern VALUE oj_slash_string; @@ -370,6 +371,7 @@ extern ID oj_utc_id; extern ID oj_utc_offset_id; extern ID oj_utcq_id; extern ID oj_write_id; +extern ID oj_method_defined_p_id; extern bool oj_use_hash_alt; extern bool oj_use_array_alt;