Skip to content

Commit dc3e8e3

Browse files
committed
Add support for if/unless on associations.
1 parent 3e16114 commit dc3e8e3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/active_model/serializer/associations.rb

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

9191
Enumerator.new do |y|
9292
self.class._reflections.each do |reflection|
93+
next unless reflection.included?(self)
9394
key = reflection.options.fetch(:key, reflection.name)
9495
next unless include_tree.key?(key)
9596
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)