From eb1264ad99678fea6cf8f4c1cf68a2bfe5b3d3a0 Mon Sep 17 00:00:00 2001 From: Benjamin Fleischer Date: Thu, 17 Sep 2015 14:47:11 -0500 Subject: [PATCH] Better serializer registration, get more than just the first module But is potentially breaking anyone on rc3, but the fix is just to manually register the adapter with the rc3-style name --- lib/active_model/serializer/adapter.rb | 14 +++++++++----- test/serializers/adapter_for_test.rb | 6 +++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/lib/active_model/serializer/adapter.rb b/lib/active_model/serializer/adapter.rb index 35f356862..6b5686b57 100644 --- a/lib/active_model/serializer/adapter.rb +++ b/lib/active_model/serializer/adapter.rb @@ -38,12 +38,16 @@ def adapters # Adds an adapter 'klass' with 'name' to the 'adapter_map' # Names are stringified and underscored - # @param [Symbol, String] name of the registered adapter - # @param [Class] klass - adapter class itself + # @param name [Symbol, String, Class] name of the registered adapter + # @param klass [Class] adapter class itself, optional if name is the class # @example # AMS::Adapter.register(:my_adapter, MyAdapter) - def register(name, klass) - adapter_map.update(name.to_s.underscore => klass) + # @note The registered name strips out 'ActiveModel::Serializer::Adapter::' + # so that registering 'ActiveModel::Serializer::Adapter::Json' and + # 'Json' will both register as 'json'. + def register(name, klass = name) + name = name.to_s.gsub(/\AActiveModel::Serializer::Adapter::/, ''.freeze) + adapter_map.update(name.underscore => klass) self end @@ -78,7 +82,7 @@ def find_by_name(adapter_name) # Automatically register adapters when subclassing def self.inherited(subclass) - ActiveModel::Serializer::Adapter.register(subclass.to_s.demodulize, subclass) + ActiveModel::Serializer::Adapter.register(subclass) end attr_reader :serializer, :instance_options diff --git a/test/serializers/adapter_for_test.rb b/test/serializers/adapter_for_test.rb index 5bab05ae4..ae7c95bb8 100644 --- a/test/serializers/adapter_for_test.rb +++ b/test/serializers/adapter_for_test.rb @@ -138,14 +138,14 @@ def test_inherited_adapter_hooks_register_adapter Object.send(:remove_const, :MyAdapter) end - def test_inherited_adapter_hooks_register_demodulized_adapter + def test_inherited_adapter_hooks_register_namespaced_adapter Object.const_set(:MyNamespace, Module.new) MyNamespace.const_set(:MyAdapter, Class.new) my_adapter = MyNamespace::MyAdapter ActiveModel::Serializer::Adapter.inherited(my_adapter) - assert_equal ActiveModel::Serializer::Adapter.lookup(:my_adapter), my_adapter + assert_equal ActiveModel::Serializer::Adapter.lookup(:'my_namespace/my_adapter'), my_adapter ensure - ActiveModel::Serializer::Adapter.adapter_map.delete('my_adapter'.freeze) + ActiveModel::Serializer::Adapter.adapter_map.delete('my_namespace/my_adapter'.freeze) MyNamespace.send(:remove_const, :MyAdapter) Object.send(:remove_const, :MyNamespace) end