Allow passing procs with variable arguments when declaring an attribute

This commit is contained in:
Erol 2018-07-13 12:35:43 +08:00 committed by Shishir Kakaraddi
parent 49193ab8f3
commit 449c1bf05f
2 changed files with 18 additions and 2 deletions

View File

@ -11,7 +11,7 @@ module FastJsonapi
def serialize(record, serialization_params, output_hash)
if include_attribute?(record, serialization_params)
output_hash[key] = if method.is_a?(Proc)
method.arity == 1 ? method.call(record) : method.call(record, serialization_params)
method.arity.abs == 1 ? method.call(record) : method.call(record, serialization_params)
else
record.public_send(method)
end
@ -26,4 +26,4 @@ module FastJsonapi
end
end
end
end
end

View File

@ -230,6 +230,22 @@ describe FastJsonapi::ObjectSerializer do
expect(serializable_hash[:data][:attributes][:title_with_year]).to eq "#{movie.name} (#{movie.release_year})"
end
end
context 'with &:proc' do
before do
movie.release_year = 2008
MovieSerializer.attribute :released_in_year, &:release_year
end
after do
MovieSerializer.attributes_to_serialize.delete(:released_in_year)
end
it 'returns correct hash when serializable_hash is called' do
expect(serializable_hash[:data][:attributes][:name]).to eq movie.name
expect(serializable_hash[:data][:attributes][:released_in_year]).to eq movie.release_year
end
end
end
describe '#link' do