From 401362d00fa707eefea1e290d7b15221f3525afc Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 30 Jun 2020 13:47:31 +0200 Subject: [PATCH] Fix detection for the json_gem adapter * JSON::JSON_LOADED is also set by json/pure and so it is not enough to detect if the JSON native extension is loaded. * JSON::Ext is not enough either, because json_pure includes json/ext.rb. * JSON::Ext::Parser is only defined if the native extension is loaded so that is reliable. * Fixes https://github.com/intridea/multi_json/issues/196 * See that issue for details. --- lib/multi_json.rb | 2 +- spec/multi_json_spec.rb | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/multi_json.rb b/lib/multi_json.rb index 02c72500..5909370d 100644 --- a/lib/multi_json.rb +++ b/lib/multi_json.rb @@ -47,7 +47,7 @@ def default_adapter return :oj if defined?(::Oj) return :yajl if defined?(::Yajl) return :jr_jackson if defined?(::JrJackson) - return :json_gem if defined?(::JSON::JSON_LOADED) + return :json_gem if defined?(::JSON::Ext::Parser) return :gson if defined?(::Gson) REQUIREMENT_MAP.each do |adapter, library| diff --git a/spec/multi_json_spec.rb b/spec/multi_json_spec.rb index 58bcc573..323bff9f 100644 --- a/spec/multi_json_spec.rb +++ b/spec/multi_json_spec.rb @@ -30,6 +30,24 @@ end end + context 'when JSON pure is already loaded' do + it 'default_adapter tries to require each adapter in turn and does not assume :json_gem is already loaded' do + require 'json/pure' + expect(JSON::JSON_LOADED).to be_truthy + + undefine_constants :Oj, :Yajl, :Gson, :JrJackson do + # simulate that the json_gem is not loaded + ext = defined?(JSON::Ext::Parser) ? JSON::Ext.send(:remove_const, :Parser) : nil + begin + expect(MultiJson).to receive(:require) + MultiJson.default_adapter + ensure + JSON::Ext::Parser = ext if ext + end + end + end + end + context 'caching' do before { MultiJson.use adapter } let(:adapter) { MultiJson::Adapters::JsonGem }