From af81a403e3384fc5f06f77867b2b48773b94b254 Mon Sep 17 00:00:00 2001 From: Alexandre de Oliveira Date: Wed, 11 Mar 2015 16:28:27 -0300 Subject: [PATCH] Passes serializer options down into associations --- lib/active_model/serializer.rb | 9 +++++---- test/fixtures/poro.rb | 4 ++++ test/serializers/associations_test.rb | 10 +++++++++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index de380336..57393d82 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -176,19 +176,20 @@ module ActiveModel end def each_association(&block) - self.class._associations.dup.each do |name, options| + self.class._associations.dup.each do |name, association_options| next unless object association = object.send(name) association_value = send(name) - serializer_class = ActiveModel::Serializer.serializer_for(association, options) + serializer_class = ActiveModel::Serializer.serializer_for(association, association_options) + serializer = serializer_class.new( association_value, - serializer_from_options(options) + serializer_from_options(association_options).merge(options) ) if serializer_class if block_given? - block.call(name, serializer, options[:association_options]) + block.call(name, serializer, association_options[:association_options]) end end end diff --git a/test/fixtures/poro.rb b/test/fixtures/poro.rb index f2862f97..d04d79dd 100644 --- a/test/fixtures/poro.rb +++ b/test/fixtures/poro.rb @@ -99,6 +99,10 @@ CommentSerializer = Class.new(ActiveModel::Serializer) do belongs_to :post belongs_to :author + + def custom_options + options + end end AuthorSerializer = Class.new(ActiveModel::Serializer) do diff --git a/test/serializers/associations_test.rb b/test/serializers/associations_test.rb index 8e3b70d5..f5976a67 100644 --- a/test/serializers/associations_test.rb +++ b/test/serializers/associations_test.rb @@ -37,7 +37,7 @@ module ActiveModel @post.author = @author @author.posts = [@post] - @post_serializer = PostSerializer.new(@post) + @post_serializer = PostSerializer.new(@post, {custom_options: true}) @author_serializer = AuthorSerializer.new(@author) @comment_serializer = CommentSerializer.new(@comment) end @@ -65,6 +65,14 @@ module ActiveModel end end + def test_serializer_options_are_passed_into_associations_serializers + @post_serializer.each_association do |name, association| + if name == :comments + assert association.first.custom_options[:custom_options] + end + end + end + def test_belongs_to assert_equal( { post: { type: :belongs_to, association_options: {} },