Skip to content

Commit d9c6805

Browse files
committed
Refactor.
1 parent 343f8b9 commit d9c6805

File tree

1 file changed

+21
-25
lines changed

1 file changed

+21
-25
lines changed

lib/active_model/serializer/adapter/json_api.rb

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,7 @@ def resource_identifier(serializer)
5050
else
5151
serializer.object.class.model_name.singular
5252
end
53-
id = serializer.id.to_s if serializer.respond_to?('id')
54-
id ||= serializer.object.id.to_s
53+
id = serializer.respond_to?('id') ? serializer.id.to_s : serializer.object.id.to_s
5554

5655
{ id: id, type: type }
5756
end
@@ -85,25 +84,18 @@ def add_included(resource_name, serializers, parent = nil)
8584

8685
def attributes_for_serializer(serializer, options)
8786
if serializer.respond_to?(:each)
88-
result = []
89-
serializer.each do |object|
90-
result << resource_object_for(object, options)
91-
end
87+
serializer.map { |s| resource_object_for(s, options) }
9288
else
93-
result = resource_object_for(serializer, options)
89+
resource_object_for(serializer, options)
9490
end
95-
result
9691
end
9792

9893
def resource_object_for(serializer, options)
9994
options[:fields] = @fieldset && @fieldset.fields_for(serializer)
10095

10196
cache_check(serializer) do
102-
attributes = serializer.attributes(options)
103-
attributes.delete(:id)
104-
10597
result = resource_identifier(serializer)
106-
98+
attributes = serializer.attributes(options).except(:id)
10799
result[:attributes] = attributes if attributes.any?
108100
result
109101
end
@@ -127,25 +119,29 @@ def check_assoc(assoc)
127119
end
128120
end
129121

122+
def resource_relationship_value(serializer, options = {})
123+
if serializer.respond_to?(:each)
124+
serializer.map { |s| resource_identifier(s) }
125+
else
126+
if options[:virtual_value]
127+
options[:virtual_value]
128+
elsif serializer.object
129+
resurce_identifier(serializer)
130+
else
131+
nil
132+
end
133+
end
134+
end
135+
130136
def add_resource_relationships(attrs, serializer, options = {})
131137
options[:add_included] = options.fetch(:add_included, true)
132138

133-
attrs[:relationships] ||= {} if serializer.associations.any?
139+
attrs[:relationships] = {} if serializer.associations.any?
134140
serializer.associations.each do |association|
135141
key = association.key
136142
serializer = association.serializer
137-
opts = association.options
138-
value = if serializer.respond_to?(:each)
139-
serializer.map { |s| resource_identifier(s) }
140-
else
141-
if opts[:virtual_value]
142-
opts[:virtual_value]
143-
elsif serializer && serializer.object
144-
resource_identifier(serializer)
145-
else
146-
nil
147-
end
148-
end
143+
options = association.options
144+
value = resource_relationship_value(serializer, options)
149145

150146
attrs[:relationships][association.key] = { data: value }
151147

0 commit comments

Comments
 (0)