Skip to content

Commit

Permalink
Merge pull request #1172 from bf4/better_adapter_registration
Browse files Browse the repository at this point in the history
Better serializer registration, get more than just the first module
  • Loading branch information
NullVoxPopuli committed Sep 18, 2015
2 parents e0a0ad3 + eb1264a commit 701eb17
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
14 changes: 9 additions & 5 deletions lib/active_model/serializer/adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
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 701eb17

Please sign in to comment.