Skip to content

Commit 6860318

Browse files
committed
Add support for if/unless on associations.
1 parent a502b5d commit 6860318

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Breaking changes:
1616

1717
Features:
1818

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

lib/active_model/serializer/associations.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ def associations(include_tree = DEFAULT_INCLUDE_TREE)
8888

8989
Enumerator.new do |y|
9090
self.class._reflections.each do |reflection|
91+
next unless reflection.included?(self)
9192
key = reflection.options.fetch(:key, reflection.name)
9293
next unless include_tree.key?(key)
9394
y.yield reflection.build_association(self, instance_options)

lib/active_model/serializer/reflection.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,18 @@ def value(instance)
3535
end
3636
end
3737

38+
# @api private
39+
def included?(serializer)
40+
case condition_type
41+
when :if
42+
serializer.public_send(condition)
43+
when :unless
44+
!serializer.public_send(condition)
45+
else
46+
true
47+
end
48+
end
49+
3850
# Build association. This method is used internally to
3951
# build serializer's association by its reflection.
4052
#
@@ -79,6 +91,20 @@ def build_association(subject, parent_serializer_options)
7991

8092
private
8193

94+
def condition_type
95+
if options.key?(:if)
96+
:if
97+
elsif options.key?(:unless)
98+
:unless
99+
else
100+
:none
101+
end
102+
end
103+
104+
def condition
105+
options[condition_type]
106+
end
107+
82108
def serializer_options(subject, parent_serializer_options, reflection_options)
83109
serializer = reflection_options.fetch(:serializer, nil)
84110

0 commit comments

Comments
 (0)