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

Add serializer to association block context #1633

Merged
merged 2 commits into from
Mar 30, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add serializer to association block context
  • Loading branch information
bf4 committed Mar 30, 2016
commit ae6805eacd53b1af1f976af494b039d7d023cd24
4 changes: 3 additions & 1 deletion lib/active_model/serializer/reflection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def include_data(value = true)
def value(serializer)
@object = serializer.object
@scope = serializer.scope
# Add '@serializer' to binding for use in association block as 'serializer'
@serializer = serializer

if block
block_value = instance_eval(&block)
Expand Down Expand Up @@ -117,7 +119,7 @@ def build_association(subject, parent_serializer_options)

protected

attr_accessor :object, :scope
attr_accessor :object, :scope, :serializer

private

Expand Down
11 changes: 9 additions & 2 deletions test/adapter/json_api/relationships_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class RelationshipAuthorSerializer < ActiveModel::Serializer

has_many :roles do
meta count: object.posts.count
serializer.cached_roles
end

has_one :blog do
Expand All @@ -60,14 +61,20 @@ class RelationshipAuthorSerializer < ActiveModel::Serializer
end
meta liked: object.likes.any?
end

def cached_roles
[
Role.new(id: 'from-serializer-method')
]
end
end

def setup
@post = Post.new(id: 1337, comments: [], author: nil)
@blog = Blog.new(id: 1337, name: 'extra')
@bio = Bio.new(id: 1337)
@like = Like.new(id: 1337)
@role = Role.new(id: 1337)
@role = Role.new(id: 'from-record')
@profile = Profile.new(id: 1337)
@location = Location.new(id: 1337)
@reviewer = Author.new(id: 1337)
Expand Down Expand Up @@ -144,7 +151,7 @@ def test_relationship_block_link_meta

def test_relationship_meta
expected = {
data: [{ id: '1337', type: 'roles' }],
data: [{ id: 'from-serializer-method', type: 'roles' }],
meta: { count: 1 }
}
assert_relationship(:roles, expected)
Expand Down