Merge pull request #274 from manojmj92/master

Evaluate ids via the specified 'id_method_name' when relationships are evaluated via a block
This commit is contained in:
Shishir Kakaraddi 2018-07-23 13:26:53 -07:00 committed by GitHub
commit daf4030bb0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 43 additions and 7 deletions

View File

@ -232,7 +232,11 @@ module FastJsonapi
Relationship.new(
key: options[:key] || run_key_transform(base_key),
name: name,
id_method_name: options[:id_method_name] || "#{base_serialization_key}#{id_postfix}".to_sym,
id_method_name: compute_id_method_name(
options[:id_method_name],
"#{base_serialization_key}#{id_postfix}".to_sym,
block
),
record_type: options[:record_type] || run_key_transform(base_key_sym),
object_method_name: options[:object_method_name] || name,
object_block: block,
@ -244,6 +248,14 @@ module FastJsonapi
)
end
def compute_id_method_name(custom_id_method_name, id_method_name_from_relationship, block)
if block.present?
custom_id_method_name || :id
else
custom_id_method_name || id_method_name_from_relationship
end
end
def compute_serializer_name(serializer_key)
return serializer_key unless serializer_key.is_a? Symbol
namespace = self.name.gsub(/()?\w+Serializer$/, '')

View File

@ -86,13 +86,11 @@ module FastJsonapi
end
def fetch_id(record, params)
unless object_block.nil?
if object_block.present?
object = object_block.call(record, params)
return object.map(&:id) if object.respond_to? :map
return object.try(:id)
return object.map { |item| item.public_send(id_method_name) } if object.respond_to? :map
return object.try(id_method_name)
end
record.public_send(id_method_name)
end
end

View File

@ -87,6 +87,31 @@ describe FastJsonapi::ObjectSerializer do
end
end
describe '#has_many with block and id_method_name' do
before do
MovieSerializer.has_many(:awards, id_method_name: :imdb_award_id) do |movie|
movie.actors.map(&:awards).flatten
end
end
after do
MovieSerializer.relationships_to_serialize.delete(:awards)
end
context 'awards is not included' do
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 }
end
serialized_award_data = hash[:data][:relationships][:awards][:data]
expect(serialized_award_data).to eq(expected_award_data)
end
end
end
describe '#belongs_to' do
subject(:relationship) { MovieSerializer.relationships_to_serialize[:area] }

View File

@ -80,6 +80,7 @@ RSpec.shared_context 'movie class' do
a.id = i
a.title = "Test Award #{i}"
a.actor_id = id
a.imdb_award_id = i * 10
a.year = 1990 + i
end
end
@ -111,7 +112,7 @@ RSpec.shared_context 'movie class' do
end
class Award
attr_accessor :id, :title, :actor_id, :year
attr_accessor :id, :title, :actor_id, :year, :imdb_award_id
end
class State