Skip to content

Commit

Permalink
allow passing proc for relationships with id_method_name
Browse files Browse the repository at this point in the history
  • Loading branch information
rishabhsairawat committed Apr 9, 2019
1 parent 83e7fb6 commit 31384e3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
9 changes: 6 additions & 3 deletions lib/fast_jsonapi/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ def serialize(record, serialization_params, output_hash)
end

def fetch_associated_object(record, params)
return object_block.call(record, params) unless object_block.nil?
record.send(object_method_name)
if object_block.present?
object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params)
else
record.send(object_method_name)
end
end

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

def fetch_id(record, params)
if object_block.present?
object = object_block.call(record, params)
object = object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params)
return object.map { |item| item.public_send(id_method_name) } if object.respond_to? :map
return object.try(id_method_name)
end
Expand Down
27 changes: 25 additions & 2 deletions spec/lib/object_serializer_class_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,31 @@
subject(:hash) { MovieSerializer.new(movie).serializable_hash }

it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do
expected_award_data = movie.actors.map(&:awards).flatten.map do |actor|
{ id: actor.imdb_award_id.to_s, type: actor.class.name.downcase.to_sym }
expected_award_data = movie.actors.map(&:awards).flatten.map do |award|
{ id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym }
end
serialized_award_data = hash[:data][:relationships][:awards][:data]

expect(serialized_award_data).to eq(expected_award_data)
end
end
end

describe '#has_many with proc and id_method_name' do
before do
ActorSerializer.has_many(:awards, id_method_name: :imdb_award_id, &:awards)
end

after do
ActorSerializer.relationships_to_serialize.delete(:awards)
end

context 'awards is not included' do
subject(:hash) { ActorSerializer.new(actor).serializable_hash }

it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do
expected_award_data = actor.awards.flatten.map do |award|
{ id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym }
end
serialized_award_data = hash[:data][:relationships][:awards][:data]

Expand Down

0 comments on commit 31384e3

Please sign in to comment.