Add support for if/unless on associations.

This commit is contained in:
Lucas Hosseini 2015-12-30 17:25:41 +01:00
parent a502b5d38b
commit 6860318133
3 changed files with 28 additions and 0 deletions

View File

@ -16,6 +16,7 @@ Breaking changes:
Features:
- [#1403](https://github.com/rails-api/active_model_serializers/pull/1403) Add support for if/unless on attributes/associations (@beauby)
- [#1248](https://github.com/rails-api/active_model_serializers/pull/1248) Experimental: Add support for JSON API deserialization (@beauby)
- [#1378](https://github.com/rails-api/active_model_serializers/pull/1378) Change association blocks
to be evaluated in *serializer* scope, rather than *association* scope. (@bf4)

View File

@ -88,6 +88,7 @@ module ActiveModel
Enumerator.new do |y|
self.class._reflections.each do |reflection|
next unless reflection.included?(self)
key = reflection.options.fetch(:key, reflection.name)
next unless include_tree.key?(key)
y.yield reflection.build_association(self, instance_options)

View File

@ -35,6 +35,18 @@ module ActiveModel
end
end
# @api private
def included?(serializer)
case condition_type
when :if
serializer.public_send(condition)
when :unless
!serializer.public_send(condition)
else
true
end
end
# Build association. This method is used internally to
# build serializer's association by its reflection.
#
@ -79,6 +91,20 @@ module ActiveModel
private
def condition_type
if options.key?(:if)
:if
elsif options.key?(:unless)
:unless
else
:none
end
end
def condition
options[condition_type]
end
def serializer_options(subject, parent_serializer_options, reflection_options)
serializer = reflection_options.fetch(:serializer, nil)