Skip to content

Commit

Permalink
Better serializer registration, get more than just the first module
Browse files Browse the repository at this point in the history
But is potentially breaking anyone on rc3, but the fix is just
to manually register the adapter with the rc3-style name
  • Loading branch information
bf4 committed Sep 18, 2015
1 parent ee40e9f commit edf30bb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
15 changes: 10 additions & 5 deletions lib/active_model/serializer/adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,17 @@ 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
name.gsub!('ActiveModel::Serializer::Adapter::'.freeze, ''.freeze)
adapter_map.update(name.underscore => klass)
self
end

Expand Down Expand Up @@ -78,7 +83,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
Expand Down
6 changes: 3 additions & 3 deletions test/serializers/adapter_for_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit edf30bb

Please sign in to comment.