Skip to content

Commit 0c70d7c

Browse files
committed
Optional dictionary for polymorphic associations
1 parent 2e8afd4 commit 0c70d7c

File tree

3 files changed

+13
-7
lines changed

3 files changed

+13
-7
lines changed

lib/fast_jsonapi/serialization_core.rb

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,25 @@ def ids_hash(ids, record_type)
2626
id_hash(ids, record_type) # ids variable is just a single id here
2727
end
2828

29-
def id_hash_from_record(record)
30-
{ id: record.id.to_s, type: record.class.name.underscore.to_sym }
29+
def id_hash_from_record(record, record_types = nil)
30+
record_type = record_types.respond_to?(:key) ? record_types[record.class] : nil
31+
{ id: record.id.to_s, type: (record_type || record.class.name.underscore.to_sym) }
3132
end
3233

3334
def ids_hash_from_record_and_relationship(record, relationship)
35+
polymorphic = relationship[:polymorphic]
36+
3437
return ids_hash(record.send(relationship[:id_method_name]), relationship[:record_type]) \
35-
unless relationship[:polymorphic]
38+
unless polymorphic
3639

3740
object_method_name = relationship.fetch(:object_method_name, relationship[:name])
3841
return unless associated_object = record.send(object_method_name)
3942

40-
return id_hash_from_record(associated_object) unless associated_object.respond_to? :map
41-
associated_object.map { |object| id_hash_from_record(object) }
43+
return associated_object.map do |object|
44+
id_hash_from_record object, polymorphic
45+
end if associated_object.respond_to? :map
46+
47+
id_hash_from_record associated_object, polymorphic
4248
end
4349

4450
def attributes_hash(record)

spec/lib/object_serializer_performance_spec.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def run_json_benchmark(message, movie_count, our_serializer, ams_serializer)
112112

113113
context 'when comparing with AMS 0.10.x and with polymorphic has_many' do
114114
[1, 25, 250, 1000].each do |group_count|
115-
speed_factor = 5
115+
speed_factor = 25
116116
it "should serialize #{group_count} records at least #{speed_factor} times faster than AMS" do
117117
ams_groups = build_ams_groups(group_count)
118118
groups = build_groups(group_count)

spec/shared/contexts/group_context.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class GroupSerializer
2222
include FastJsonapi::ObjectSerializer
2323
set_type :group
2424
attributes :name
25-
has_many :groupees, polymorphic: true
25+
has_many :groupees, polymorphic: { Person => :person, Group => :group }
2626
end
2727
end
2828

0 commit comments

Comments
 (0)