Skip to content

Commit 58f598b

Browse files
committed
Add if/unless support to associations.
1 parent bcd428e commit 58f598b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/active_model/serializer/associations.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ def associations(include_tree = DEFAULT_INCLUDE_TREE)
9191
Enumerator.new do |y|
9292
self.class._reflections.each do |reflection|
9393
key = reflection.options.fetch(:key, reflection.name)
94+
next unless reflection.include?(self)
9495
next unless include_tree.key?(key)
9596
y.yield reflection.build_association(self, instance_options)
9697
end

lib/active_model/serializer/reflection.rb

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,20 @@ class Serializer
2525
#
2626
# So you can inspect reflections in your Adapters.
2727
#
28-
Reflection = Struct.new(:name, :options, :block) do
28+
Reflection = Struct.new(:name, :options, :block, :condition_type, :condition) do
29+
def initialize(name, options, block = nil)
30+
super(name, options, block)
31+
self.condition_type =
32+
if options.key?(:if)
33+
:if
34+
elsif options.key?(:unless)
35+
:unless
36+
else
37+
:none
38+
end
39+
self.condition = options[condition_type]
40+
end
41+
2942
# @api private
3043
def value(instance)
3144
if block
@@ -35,6 +48,18 @@ def value(instance)
3548
end
3649
end
3750

51+
# @api private
52+
def include?(serializer)
53+
case condition_type
54+
when :if
55+
serializer.send(condition)
56+
when :unless
57+
!serializer.send(condition)
58+
else
59+
true
60+
end
61+
end
62+
3863
# Build association. This method is used internally to
3964
# build serializer's association by its reflection.
4065
#

0 commit comments

Comments
 (0)