Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

:serializer option now can take a symbol as a method to call. #865

Open
wants to merge 1 commit into
base: 0-8-stable
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/active_model/serializer/associations.rb
Expand Up @@ -48,7 +48,13 @@ def option(key, default=nil)

def target_serializer
serializer = option(:serializer)
serializer.is_a?(String) ? serializer.constantize : serializer
if serializer.is_a?(String)
serializer.constantize
elsif serializer.is_a?(Symbol)
source_serializer.send(serializer)
else
serializer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting point. I'm not really sure what I think about it.

This code could be

case serializer
when String then serializer.constantize
when Symbol then source_serializer.send(serializer)
else serializer
end

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks a bit cleaner (the case/when)

end
end

def source_serializer
Expand Down
26 changes: 26 additions & 0 deletions test/association_test.rb
Expand Up @@ -589,4 +589,30 @@ def test_specifying_serializer_class_as_string
assert_equal({}, @root_hash)
end
end

class SymbolSerializerOption < AssociationTest
class SymbolSerializer < ActiveModel::Serializer
attributes :id
end

def test_specifying_serializer_class_as_a_symbol
@post_serializer_class.class_eval do
has_many :comments, :embed => :objects

def conditional_searializer
AssociationTest::SymbolSerializerOption::SymbolSerializer
end
end

include_bare! :comments, :serializer => :conditional_searializer

assert_equal({
:comments => [
{ :id => 1 }
]
}, @hash)

assert_equal({}, @root_hash)
end
end
end