Skip to content

Commit 31384e3

Browse files
allow passing proc for relationships with id_method_name
1 parent 83e7fb6 commit 31384e3

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

lib/fast_jsonapi/relationship.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,11 @@ def serialize(record, serialization_params, output_hash)
4747
end
4848

4949
def fetch_associated_object(record, params)
50-
return object_block.call(record, params) unless object_block.nil?
51-
record.send(object_method_name)
50+
if object_block.present?
51+
object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params)
52+
else
53+
record.send(object_method_name)
54+
end
5255
end
5356

5457
def include_relationship?(record, serialization_params)
@@ -96,7 +99,7 @@ def id_hash(id, record_type, default_return=false)
9699

97100
def fetch_id(record, params)
98101
if object_block.present?
99-
object = object_block.call(record, params)
102+
object = object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params)
100103
return object.map { |item| item.public_send(id_method_name) } if object.respond_to? :map
101104
return object.try(id_method_name)
102105
end

spec/lib/object_serializer_class_methods_spec.rb

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,31 @@
102102
subject(:hash) { MovieSerializer.new(movie).serializable_hash }
103103

104104
it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do
105-
expected_award_data = movie.actors.map(&:awards).flatten.map do |actor|
106-
{ id: actor.imdb_award_id.to_s, type: actor.class.name.downcase.to_sym }
105+
expected_award_data = movie.actors.map(&:awards).flatten.map do |award|
106+
{ id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym }
107+
end
108+
serialized_award_data = hash[:data][:relationships][:awards][:data]
109+
110+
expect(serialized_award_data).to eq(expected_award_data)
111+
end
112+
end
113+
end
114+
115+
describe '#has_many with proc and id_method_name' do
116+
before do
117+
ActorSerializer.has_many(:awards, id_method_name: :imdb_award_id, &:awards)
118+
end
119+
120+
after do
121+
ActorSerializer.relationships_to_serialize.delete(:awards)
122+
end
123+
124+
context 'awards is not included' do
125+
subject(:hash) { ActorSerializer.new(actor).serializable_hash }
126+
127+
it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do
128+
expected_award_data = actor.awards.flatten.map do |award|
129+
{ id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym }
107130
end
108131
serialized_award_data = hash[:data][:relationships][:awards][:data]
109132

0 commit comments

Comments
 (0)